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

Solution1:  Brute-force

Lock pointer i,  move pointer j to check if nums[j] == target - nums[i].

         

       

code:

 1 /* Time Complexity: O(n*n)
 2    Space Complexity: O(1)
 3 */
 4 class Solution {
 5     public int[] twoSum(int[] nums, int target) {
 6         for (int i = 0; i < nums.length; i++) {
 7             for (int j = i + 1; j < nums.length; j++) {
 8                 if (nums[j] == target - nums[i]) {
 9                     return new int[] { i, j };
10                 }
11             }
12         }
13         return null;
14     }
15 }

Solution2: HashMap

Use a map to record the index of each element and check if target - nums[i] is in the map. if so, we find a pair whose sum is equal to target.

code:

 1 /* Time Complexity: O(n)
 2    Space Complexity: O(n)
 3 */
 4 class Solution {
 5     public int[] twoSum(int[] nums, int target) {
 6         Map<Integer, Integer> map = new HashMap<>();
 7         for(int i = 0; i< nums.length; i++){
 8             if(map.containsKey(target - nums[i])){
 9                 return new int[]{i, map.get(target - nums[i])};
10             }else{
11                 map.put(nums[i], i);
12             }
13         }
14         return null;
15     }
16 }

                      

原文地址:https://www.cnblogs.com/liuliu5151/p/9080911.html