leetcode第1题two sum

Two Sum

Two Sum的题目要求是,给定一个数组和一个目标值,求得数组中两数num1num2相加等于目标值target的两个数的下标。解法有两种,一是暴力法,一个个比较过来;二是哈希,把数组存在map里,存放的过程中只要发现map里面存有num1对应的目标解num2=target-num1,则返回下标即可。

Solution

下面是Java的代码:

class Solution {
    public int[] twoSum(int[] nums,int target){
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++){
            for (int j = i + 1;j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                }
            }
        }
        return result;
    }
}
class Solution {
    public int[] twoSum(int[] nums,int target){
        int[] result = new int[2];
        Map<Integer,Integer> mp = new HashMap<Integer, Integer>();
        for (int i  = 0; i < nums.length; i++){
            if(mp.containsKey(target - nums[i])){
                result[0] = mp.get(target - nums[i]);
                result[1] = i;
                return  result;
            }
            mp.put(nums[i],i);
        }
        return result;
    }
}

下面是Python的代码:

class Solution:
    def twoSum(self, nums, target: int):
        mp = {}
        for i, x in enumerate(nums):
            if x in mp:
                return mp[x], i
            else:
                mp[target - x] = i
        return -1

总结

第1题是简单题,迈出了第一步,以后也不要停下噢!


本文作者:WenQian Dong
版权声明:本博客所有文章除特别声明外,均采用
CC BY-NC-SA 3.0 许可协议。转载请注明出处!


本文链接:https://wqdchn.github.io/leetcode-two-sum.html