[LC]1 Two Sum

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LC]1 Two Sum相关的知识,希望对你有一定的参考价值。

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].






思路一:两个for loop,干掉,千万别用。
思路二:用map先loop一遍存起来,然后再loop一遍数组,看target-current这个差值存不存在map里。
思路二优化:把两次loop合并成一次loop:
       public int[] twoSum(int[] nums, int target){
         int[] res = new int[2];
         HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
         for(int i=0;i<nums.length;i++){
            if(map.containsKey(target-nums[i])){
                res[1]=map.get(target-nums[i]);
                res[2]=i;
                return res;
            }
            map.put(nums[i],i);
        }

        return res;
     }

 



 



  

以上是关于[LC]1 Two Sum的主要内容,如果未能解决你的问题,请参考以下文章

[LC] 1214. Two Sum BSTs

LC1 Two Sum

LC 599. Minimum Index Sum of Two Lists

[LC] 170. Two Sum III - Data structure design

[LC] 167. Two Sum II - Input array is sorted

[LC] 1099. Two Sum Less Than K