美文网首页
LeetCode--1. Two Sum java/pytho

LeetCode--1. Two Sum java/pytho

作者: 姜小姜小 | 来源:发表于2019-02-28 08:47 被阅读0次

陆陆续续在LeetCode上刷了一些题,一直没有记录过,准备集中整理记录一下

java:
class Solution {
    public int[] twoSum(int[] nums, int target) {
       int[] arr = {-1, -1};
        for (int i = 0; i < nums.length; i++) {
            for (int j = i; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    arr[0] = i;
                    arr[1] = j;
                    return arr;
                }
            }
        }
       return null;
    }
}



python:
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for index, num in enumerate(nums):
            if (target - num) in d:
                return [index, d[target - num]]
            d[num] = index

相关文章

网友评论

      本文标题:LeetCode--1. Two Sum java/pytho

      本文链接:https://www.haomeiwen.com/subject/qkvcuqtx.html