[LeetCode] 1. Two Sum 两数和

版权声明:流浪者 https://blog.csdn.net/gz153016/article/details/87889833

Given an array of integers, return indices(索引,下标) of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

给一个包含整数的数组,找出使得两个数的和是给定值的indices(索引,下标)。假设每个输入只有一个答案, 同一元素不会用到两次。

解法:

  1. 暴力解法,两个for循环遍历,两个数相加和目标数比较。Time: O(n^2)

  2. 先遍历一遍数组,建立数字和index的HashMap,然后再遍历一遍,开始查找target - num[i]是否在map中,如果在,找到并返回index。Time: O(n) Space: O(n)

Java:解法1

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res=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){
                    res[0]=i;
                    res[1]=j;
                }
            }
        }
        return res;
    }
}

Java:解法2

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer>hashmap=new HashMap<Integer,Integer>();
        int[]res=new int[2];
        for(int i=0;i<nums.length;++i)
            hashmap.put(nums[i],i);
        for(int i=0;i<nums.length;++i){
            int temp=target-nums[i];
            if(hashmap.containsKey(temp) && hashmap.get(temp)!=i){
                res[0]=i;
                res[1]=hashmap.get(temp);
            }
        }
        return res;
    }
}

Java:解法2

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

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        
        hash_map={}
        for i,value in enumerate(nums):
            hash_map[value]=i
        for index1,value in enumerate(nums):
            if target-value in hash_map: #快速判断元素是否在集合内
                index2=hash_map[target-value]
                if index1!=index2:
                    return index1,index2  

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        lookup={}
        for i,value in enumerate(nums):
            if target-value in lookup:
                return lookup[target-value],i
            lookup[value]=i
        

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        lookup={}
        for i in range(len(nums)):
            if target-nums[i] in lookup:
                return lookup[target-nums[i]],i
            lookup[nums[i]]=i
        

Python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if len(nums)<=1:
            return False
        buff_dict={}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return buff_dict[nums[i]],i
            buff_dict[target-nums[i]]=i
        
        

python:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
       unordered_map<int,int> lookup;
       for(int i=0;i<nums.size();++i){
           if(lookup.count(target-nums[i])){
              return {lookup[target-nums[i]],i}; 
           }   
           lookup[nums[i]]=i;
       }
       return {};
}
};

猜你喜欢

转载自blog.csdn.net/gz153016/article/details/87889833
今日推荐