Timo66

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

n-sum problem 

Question 2

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

solution 1: Brute force. O(n*n)

复制代码
 1     public int[] twoSum(int[] nums, int target) {
 2         if(nums.length == 0)
 3             return null;
 4        
 5         for (int i = 0; i < nums.length; i ++){
 6             for (int j = i+1; j < nums.length; j ++){
 7                 if (nums[i] + nums[j] == target){
 8                     int[] result = new int[]{i+1, j+1};
 9                     return result;
10                 }
11             }
12         }
13         return null;
14     }
复制代码

 

solution 2: sort and binary search. O(n+nlogn+n+n) = O(nlogn)

复制代码
 1 public int[] twoSum(int[] nums, int target) {
 2         if(nums.length == 0)
 3             return null;
 4             
 5         int[] result = new int[2];
 6        
 7         int[] copyNums = new int[nums.length];
 8         System.arraycopy(nums, 0, copyNums, 0, nums.length);  
 9         Arrays.sort(copyNums);
10         
11         int low = 0; 
12         int high = copyNums.length-1;
13         
14         while (low < high){
15             int sum = copyNums[low] + copyNums[high];
16             if (sum == target){
17                 result[0] = copyNums[low];
18                 result[1] = copyNums[high];
19                 break;
20             }
21             else if (sum < target)
22                 low ++;
23             else
24                 high --;
25         }
26         
27         if (result.length == 0)
28             return null;
29             
30         else{
31             int index1 = -1, index2 = -1;
32             for (int i = 0; i < nums.length; i ++){
33                 if (result[0] == nums[i] && index1 == -1)
34                     index1 = i + 1;
35                 else if (result[1] == nums[i] && index2 == -1)
36                     index2 = i + 1;
37             }
38             
39             result[0] = index1;
40             result[1] = index2;
41             Arrays.sort(result);
42             return result;
43         }
44     }
复制代码

 

solution 2: hashmap. O(n)

复制代码
 1     public int[] twoSum(int[] nums, int target) {
 2         if(nums.length < 2 || nums == null)
 3             return null;
 4             
 5         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 6         int[] res = new int[2];
 7         
 8         for (int i = 0; i < nums.length; i ++){
 9             if (!map.containsKey(target-nums[i]))
10                 map.put(nums[i], i + 1);
11             else{
12                 res[0] = map.get(target-nums[i]);
13                 res[1] = i + 1;
14                 break;
15             }
16         }
17         return res;
18     }
复制代码

 Question 3

3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
    For example, given array S = {-1 0 1 2 -1 -4},
    A solution set is:
    (-1, 0, 1)
    (-1, -1, 2)

 I feel this is much more difficult than the before 2 sum one. We need three pointers here. And I found a trick, with which you did not write tree times list.add(element).

Arrays.asList(a, b, c) 
复制代码
 1     public List<List<Integer>> threeSum(int[] nums) {
 2         List<List<Integer>> triples = new ArrayList();
 3         if (nums.length < 3)
 4             return triples;
 5         
 6         Arrays.sort(nums);
 7         int i = 0, last = nums.length - 1;
 8         while (i < last) {
 9             int a = nums[i], j = i+1, k = last;
10             while (j < k) {
11                 int b = nums[j], c = nums[k], sum = a+b+c;
12                 if (sum == 0) triples.add(Arrays.asList(a, b, c));
13                 if (sum <= 0) while (nums[j] == b && j < k) j++;
14                 if (sum >= 0) while (nums[k] == c && j < k) k--;
15             }
16             while (nums[i] == a && i < last) i++;
17         }
18         return triples;
19     }
复制代码

Question 4

3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
 1 public int threeSumClosest(int[] nums, int target) {
 2         if (nums.length < 3)
 3             return Integer.MAX_VALUE;
 4         
 5         Arrays.sort(nums);
 6         int result = nums[0] + nums[1] + nums[2];
 7             
 8         int i = 0;
 9         int last = nums.length - 1;
10         while (i < last){
11             int a = nums[i];
12             int j = i + 1;
13             int k = last;
14             while (j < k){
15                 int b = nums[j];
16                 int c = nums[k];
17                 int sum = a + b + c;
18                 int diff = Math.abs(target - sum);
19                 
20                 if (diff < Math.abs(target - result)){
21                     result = sum;
22                 }
23                 
24                 if (diff == 0)
25                     return sum;
26                 else if (sum > target){
27                     while (nums[k] == c && j < k)
28                         k --;
29                 }
30                 else if (sum < target){
31                     while (nums[j] == b && j < k)
32                         j ++;
33                 }
34             }
35             while (nums[i] == a && i < k)
36                 i ++;
37         }
38         return result;
39         
40     }

Question 5

4Sum

Given an array S of n integers, are there elements abc, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

  • Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
  • The solution set must not contain duplicate quadruplets.

 

    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)
 For this problem, use 4 sum nests 3 sum nesting 2 sum and then get the result. Make 3 pointer move forward from the begining and one pointer move backward. One thing we need to remember the i < nums.length-2 at lease leave the length -1, length-2 for other pointer.
 1 public List<List<Integer>> fourSum(int[] nums, int target) {
 2         List<List<Integer>> res = new ArrayList<List<Integer>>();
 3         if (nums.length < 4)
 4             return res;
 5             
 6         Arrays.sort(nums);
 7         
 8         int i = 0; 
 9         int last = nums.length - 1 ;
10         HashSet<List<Integer>> set = new HashSet<List<Integer>>();
11         int n1 = nums[0], n2 = nums[1], n3 = nums[2], n4 = nums[last];
12         
13         while (i < last){
14             int j = i + 1;
15             n1 = nums[i]; 
16             while (j < last){
17                 int m = j + 1;
18                 int k = last;
19                 n2=nums[j];
20                 while (m < k){
21                      n3=nums[m]; n4=nums[k];
22                     int sum = n1 + n2 + n3 + n4;
23                     if (sum == target){
24                         if (!set.contains(Arrays.asList(n1,n2,n3,n4))){
25                             res.add(Arrays.asList(n1,n2,n3,n4));
26                             set.add(Arrays.asList(n1,n2,n3,n4));
27                         }
28                     }
29                     if (sum <= target){
30                         while (n3 == nums[m] && m < k)
31                             m ++;
32                     }
33                     if (sum >= target){
34                         while (n4 == nums[k] && m < k)
35                             k --;
36                     }
37                 }
38                 while (n2 == nums[j] && j < last)
39                     j ++;
40             }
41             while (n1 == nums[i] && i < last)
42                 i ++;
43         }
44         return res;
45     }

Question 6

 TwoSum II - Input array is sorted

/*Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

This problem is very similar to the two sum and even eaiser as it is already sorted.

 1 public int[] twoSum(int[] num, int target){
 2     
 3     if (num.length < 1 || num == null)
 4         return num;
 5 
 6     int p1 = 0;
 7     int p2 = num.length - 1;
 8     int[] res = new int[2];
 9 
10     while (p1 < p2){
11         int sum = num[p1] + num[p2];
12         if (sum == target){
13             res[0] = p1+1;
14             res[1] = p2+1;
15             return res;
16         }
17         else if (sum < target){
18             p1 ++;
19         }
20         else{
21             p2 ++;
22         }
23     }
24     return null;
25            
26 } 

Question 7

170 Two Sum III - Data structure design
Design and implement a TwoSum class. It should support the following operations:add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false

Use hashmap here is very convenient. One thing need to remember is the may be the correct two digits are the same, in which case we should also consider it.

For key iterator use hashMap.keySet(); For value iterator use hashMap.value();

 1 public class twoSum{
 2     HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 3 
 4     pubilc void add(int value){
 5         if (map.containsKey(value)){
 6             map.put(value, map.get(value)+1);
 7         }
 8         else{
 9             map.put(value,1);
10         }
11     }
12 
13     public boolean find(int target){
14         for (int key : map.keySet()){
15             int another = target - key;
16             if (map.containsKey(another)){
17                 if (another == key){
18                     if (map.get(another) > 1){
19                         return true;
20                     }
21                     else{
22                         return false;
23                     }
24                 }
25             }
26         }
27         return false;
28     }
29 }

 

 

 
posted on 2015-07-21 21:42  Timo66  阅读(172)  评论(0编辑  收藏  举报