K-sum

2017-04-10  本文已影响0人  Arrrrrrk

1. 2sum

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.

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

public class Solution {
    public int[] twoSum(int[] nums, int target) {
     Map<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] = m.get(target - nums[i]);
             res[1] = i;
             break;
         }
         m.put(nums[i], i); 
     }
     return res;
    }
}

2. 2sum II:

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 and you may not use the same element twice.

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

public class Solution {
    public int[] twoSum(int[] num, int target) {
    int[] indice = new int[2];
    //边界判断是很重要的。
    if (num == null || num.length < 2) return indice;
    int left = 0, right = num.length - 1;
    while (left < right ) {
    //这里其实需要防止int相加溢出,可以用long
        if (num[left] + num[right] == target) {
            indice[0] = left + 1;
            indice[1] = right + 1;
            break;
        } 
        else if (num[left] + num[right] > target) right--;
        else left ++;
    }
    return indice;
}
}

3. 3sum

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

Note: 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]
]

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
        if(nums == null || nums.length < 3)return result;
        Arrays.sort(nums);
        
        for(int i = 0; i < nums.length - 2; i++){
            if(nums[i >0])break; 
            //nums[i] > nums[i-1] to avoid duplicate solutuions
            if(i == 0 || nums[i] > nums[i-1]){
                int opp = -nums[i];
                int l = i +1;
                int r = nums.length-1;
                while(l < r){
                    if(nums[l]+nums[r] == opp){
                        List<Integer> temp = new ArrayList<Integer>();
                        // already sorted
            //res.add(Arrays.asList(num[i], num[l], num[R]));
                        temp.add(nums[i]);
                        temp.add(nums[l]);
                        temp.add(nums[r]);
                        result.add(temp);
                        //change both l & r
                        l++;
                        r--;
                        //avoid duplicate solutuions
                        while(l < r && nums[l] == nums[l-1])l++;
                        while(l < r && nums[r] == nums[r+1])r--;
                        
                    }else if(nums[l]+nums[r] > opp)r--;
                    else l++;
                }
            }
        }

    return result;
    }
}

学习一下别人的代码风格(但是RT会增加,?)

public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if(nums.length < 3) return result;
        Arrays.sort(nums);
        int i = 0;
        while(i < nums.length - 2) {
            if(nums[i] > 0) break;
            int j = i + 1;
            int k = nums.length - 1;
            while(j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if(sum == 0) result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                if(sum <= 0) while(nums[j] == nums[++j] && j < k);
                if(sum >= 0) while(nums[k--] == nums[k] && j < k);
            }
            while(nums[i] == nums[++i] && i < nums.length - 2);
        }
        return result;
    }
}

4. 4sum

Given an array S of n integers, are there elements a, b, c, 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: 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]
]

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
        if(nums == null || nums.length < 4)return result;
        Arrays.sort(nums);
        
        for(int p = 0;  p < nums.length-3; p++ ){
            //if(nums[p]>target)return result;当target<0时不成立。如(-5) > (-9), (-5)+(-4) = (-9)
            if(p == 0 || nums[p] > nums[p-1]){
                int res = target -nums[p];
                for(int i = p+1; i < nums.length - 2; i++){
                    //if(nums[i] > res)break; 
                    //nums[i] > nums[i-1] to avoid duplicate solutuions
                    if(i == p+1 || nums[i] > nums[i-1]){
                        int opp = res -nums[i];
                        int l = i +1;
                        int r = nums.length-1;
                        while(l < r){
                            if(nums[l]+nums[r] == opp){
                            List<Integer> temp = new ArrayList<Integer>();
                            // already sorted
                            //res.add(Arrays.asList(num[i], num[l], num[R]));
                            temp.add(nums[p]);
                            temp.add(nums[i]);
                            temp.add(nums[l]);
                            temp.add(nums[r]);
                            result.add(temp);
                            //change both l & r
                            l++;
                            r--;
                            //avoid duplicate solutuions
                            while(l < r && nums[l] == nums[l-1])l++;
                            while(l < r && nums[r] == nums[r+1])r--;
                        
                            }else if(nums[l]+nums[r] > opp)r--;
                            else l++;
                        }
                    }
                }
            }
        } 
    return result;
    }
}  

另一种Hash方法,RT=O(n^2)。

上一篇 下一篇

猜你喜欢

热点阅读