Two Sum leetcode第一题

Question Description :  Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.You may assume that each input would have exactly one solution, and you may not use the same element twice.You can return the answer in any order.

翻译:给定一个整形数组nums以及一个整数target,返回数组中两个数的下标,并且这两个数满足两者相加能够等于target,你可以假定每次给定一个target,满足这个条件的解只有一个,这就意味着假设给定的target值为9,那么在该数组中如果有的话,只有一组数的值,其两者相加等于target,并且你不会使用同一个值两次,这就意味着如果target为8,且这时数组中有一个数字4,因为4+4= 8

但是不能返回4的下标两次,因为重复使用同一个数值两次。你所返回的满足条件的数字的下标的顺序不做要求。

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

限制:
  • 2 <= nums.length <= 10^4  
  • -10^9 <= nums[i] <= 10^9 使用int类型的数组足够
  • -10^9 <= target <= 10^9. target的数据类型也是int类型足够
  • Only one valid answer exists      要么没有,如果有的话也是只有一个答案存在
解决方案:
//第一种方式:针对数组中的前N-1的每一个数,将数组中在其后面的数依次进行比较,并找出合适的数值进行返回。
class Solution{
    public int[] twoSum(int[] nums,int target){
        for(int i = 0;i < nums.length-1;i++){
             int complement = target - nums[i]; // 使用减来找出符合该数值的数,可以在一定程度上避免相加数值过大而造成的溢出问题。
           for(int j = i+1;;j < nums.length;j++){
             if(nums[j] == complement){
                return new int[]{i,j};  
             }
          }
       }
    return null//如果没有查找出合适的结果,就返回null
    }
}

// 第二种解决方式:因为对与数组中的complement的遍历查找太浪费时间,所以,可以使用空间换取时间的方式来进行查找
// 因为此题中返回的是数组中符合条件的数的下标,所以可以使用哈希表将下标和对应的数进行关联映射,而哈希表对于数组
// 中数的查找是近乎常量级的,近乎的原因是可能有哈希冲突的数在链表上存储,需要进行遍历。
class Solution{
    public int[] twoSum(int[] nums,int target){
        Map<Integer,Integer> map = new HashMap<>();
        for(int i = 0;i < nums.length;i++){
            map.put(nums[i],i);
        }
        for(int i = 0;i < nums.length;i++){
            int complement = target - nums[i];
            if(map.containsKey(complement) && map.get(complement) != i){
                return new int[]{i,map.get(complement)};
            }
        }
        return null;
    }
}

 

 
 
posted @ 2022-04-22 08:32  EdgerHuang  阅读(23)  评论(0)    收藏  举报