Leetcode kSum問題

6876 ワード

kSumは一般にleetcode第1題2 Sum,leetcode第15題3 Sum,leetcode第18題4 Sumのような問題を指す.
私たちはまず1題1題を見て、それからこのような問題の解題方法をまとめました.
2 Sum(leetcode第1題)
に質問
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サイクル解法(O(N^2))
public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] + nums[j] == target) {
                res[0] = i;
                res[1] = j;
                return res;
            }
        }
    }
    return res;
}

時間複雑度:O(N^2)
この解法は最も単純で直感的であるが,効率も最も低い.コミットするとすべてのtest caseを通過できず、タイムアウトするに違いありません.
ソート+two pointers(O(NlogN))
まずソートしてからtwo pointersを使用します.
public int[] twoSum(int[] nums, int target) {
    Arrays.sort(nums);
    int i = 0, j = nums.length - 1;
    int[] res = new int[2];
    while (i < j) {
        if (nums[i] + nums[j] == target) {
            res[0] = i;
            res[1] = j;
            break;
        } else if (nums[i] + nums[j] < target) {
            i++;
        } else {
            j--;
        }
    }
    return res;
}

時間複雑度:O(Nlog(N)+O(N),最終複雑度O(Nlog(N)))
HashMap一遍(O(N))
public int[] twoSum(int[] nums, int target) {
    Map map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    int j = 0, k = 0;
    for (int i = 0; i < nums.length; i++) {
        int left = target - nums[i];
        if (map.containsKey(left) && i != map.get(left)) {
            j = i;
            k = map.get(left);
            break;
        }
    }
    int[] res = new int[2];
    res[0] = j;
    res[1] = k;
    return res;
}

時間複雑度:O(N)
3 Sum(leetcode第5題)
に質問
Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

ソート+two pointers
3 Sumは2 Sumと類似しており,先に紹介した2 Sumの最初の2つの解法は3 Sumと同様に有効である.第1の解法は3層forサイクルでタイムアウトするに違いない.まずソートしてtwo pointersで問題を解きます
public List> threeSum(int[] nums) {
    if (nums == null || nums.length < 3) {
        return new ArrayList<>();
    }
    List> ret = new ArrayList<>();
    Arrays.sort(nums);
    for (int i = 0; i < nums.length - 2; i++) {
        int num = nums[i];
        if (i > 0 && nums[i] == nums[i - 1]) {
            continue;
        }
        bSearch(nums, i + 1, nums.length - 1, -num, ret, i);
    }
    return ret;
}

private void bSearch(int[] nums, int start, int end, int targetTotal, List> ret, int index) {
    int i = start, j = end;
    while (i < j) {
        if (targetTotal == nums[i] + nums[j]) {
            List oneShot = new ArrayList<>();
            oneShot.add(nums[index]);
            oneShot.add(nums[i]);
            oneShot.add(nums[j]);
            ret.add(oneShot);
            //           triple      ,               
            while (i < j && nums[i] == nums[i + 1]) {
                i++;
            }
            while (i < j && nums[j] == nums[j - 1]) {
                j--;
            }
            i++;
            j--;
        } else if (nums[i] + nums[j] > targetTotal) {
            j--;
        } else {
            i++;
        }
    }
}

時間複雑度:O(NlogN)+O(N 2),最終複雑度O(N 2)
4 Sum(leetcode第18題)
に質問
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums 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.

Example:

Given array nums = [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]
]

ぶんせき
3 Sum問題を解くときにnumの数を固定し,残りの配列要素でtwo pointers法を用いてtarget‐numの2つの数を探した.
解析をまとめると,kSumのような問題の解法を2つのステップに分けることができる.
  • kSum問題を2 Sum問題
  • に変換
  • 2解決2 Sum問題
  • kSumの問題の一般的な解法は以下の通りである.
    /**
     * All kSum problem can be divided to two parts:
     * 1: convert kSum to 2Sum problem;
     * 2: solve the 2Sum problem;
     *
     * @param k
     * @param index
     * @param nums
     * @param target
     * @return
     */
    private List> kSum(int k, int index, int[] nums, int target) {
        List> res = new ArrayList<>();
        int len = nums.length;
        if (k == 2) {
            //    two pointers    2Sum   
            int left = index, right = len - 1;
            while (left < right) {
                int sum = nums[left] + nums[right];
                if (sum == target) {
                    List path = new ArrayList<>();
                    path.add(nums[left]);
                    path.add(nums[right]);
                    res.add(path);
                    // skip the duplicates
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    left++;
                    right--;
                } else if (sum > target) {
                    right--;
                } else {
                    left++;
                }
            }
        } else {
            //   kSum       2Sum   
            for (int i = index; i < len - k + 1; i++) {
                //        
                if (i > index && nums[i] == nums[i - 1]) {
                    continue;
                }
                //       ,    
                List> kSubtractOneSum = kSum(k - 1, i + 1, nums, target - nums[i]);
                if (kSubtractOneSum != null) {
                    for (List path : kSubtractOneSum) {
                        path.add(0, nums[i]); //            
                    }
                    res.addAll(kSubtractOneSum);
                }
            }
        }
        return res;
    }
    

    kSum問題を解決した後、4 Sum問題の解法は簡単です.
    public List> fourSum(int[] nums, int target) {
        if (nums == null || nums.length < 4) {
            return new ArrayList<>();
        }
        Arrays.sort(nums);
        return kSum(4, 0, nums, target);
    }
    

    時間複雑度:O(N^3).