LeetCode关于N Sum的问题

关于我的 Leetcode 题目解答,代码前往 Github:https://github.com/chenxiangcyr/leetcode-answers


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

以下代码的时间复杂度为 O(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        // key: integer, value: the idx for the integer
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        for(int i = 0; i < nums.length; i++) {
            int rest = target - nums[i];
            
            if(map.containsKey(rest)) {
                return new int[] {i, map.get(rest)};
            }
            
            map.put(nums[i], i);
        }
        
        throw new IllegalArgumentException("no result for the input");
    }
}

LeetCode题目:167. Two Sum 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 and you may not use the same element twice.

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

以下代码的时间复杂度为 O(n)

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int low = 0;
        int high = numbers.length - 1;
        
        while (low < high) {
            int sum = numbers[low] + numbers[high];
            if (sum == target) {
                return new int[]{low + 1, high + 1};
            }
            else if (sum < target) {
                low++;
            }
            else {
                high--;
            }
        }
        
        throw new IllegalArgumentException("no result for the input");
    }
}

LeetCode题目: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

class TwoSum {
    // 记录所有的数字
    private List<Integer> list;
    
    // 记录每个数字出现的次数
    private Map<Integer, Integer> map;
    
    /** Initialize your data structure here. */
    public TwoSum() {
        list = new ArrayList<Integer>();
        map = new HashMap<Integer, Integer>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        if (map.containsKey(number)) {
            map.put(number, map.get(number) + 1);
        }
        else {
            map.put(number, 1);
            list.add(number);
        }
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for (int i = 0; i < list.size(); i++){
            int num1 = list.get(i);
            int num2 = value - num1;
            
            if ((num1 == num2 && map.get(num1) > 1) || (num1 != num2 && map.containsKey(num2))) {
                return true;
            }
        }
        
        return false;
    }
}

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * boolean param_2 = obj.find(value);
 */

LeetCode题目:15. 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]

以下代码的时间复杂度为 O(n^2)

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        return threeSum(nums, 0);
    }
    
    public List<List<Integer>> threeSum(int[] nums, int target) {
        
        List<List<Integer>> result = new ArrayList<>();
        
        // 排序
        Arrays.sort(nums);
        
        for(int i = 0; i < nums.length - 2; i++) {
            // 避免重复数字
            while(i > 0 && i < nums.length - 2 && nums[i] == nums[i - 1]) {
                i++;
            }
            
            int low_idx = i + 1;
            int high_idx = nums.length - 1;
            
            int remaining = target - nums[i];
            
            while(low_idx < high_idx) {
                if(nums[low_idx] + nums[high_idx] < remaining) {
                    low_idx++;
                }
                
                else if (nums[low_idx] + nums[high_idx] > remaining) {
                    high_idx--;
                }
                
                else {
                    result.add(Arrays.asList(nums[i], nums[low_idx], nums[high_idx]));
                    
                    // 避免重复数字
                    low_idx++;
                    while(low_idx < high_idx && nums[low_idx] == nums[low_idx - 1]) {
                        low_idx++;
                    }
                    
                    // 避免重复数字
                    high_idx--;
                    while(low_idx < high_idx && nums[high_idx] == nums[high_idx + 1]) {
                        high_idx--;
                    }
                }
            }
        }
        
        return result;
    }
}

LeetCode题目:16. 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).

以下代码的时间复杂度为 O(n^2)

class Solution {
    public int threeSumClosest(int[] nums, int target) {
        
        int result = nums[0] + nums[1] + nums[2];
        
        // 排序
        Arrays.sort(nums);
        
        for(int i = 0; i < nums.length - 2; i++) {
            int low_idx = i + 1;
            int high_idx = nums.length - 1;
            
            while(low_idx < high_idx) {
                int sum = nums[i] + nums[low_idx] + nums[high_idx];
                
                if (Math.abs(sum - target) < Math.abs(result - target)) {
                    result = sum;
                }
                
                if(sum < target) {
                    low_idx++;
                }
                else {
                    high_idx--;
                }
            }
        }
        
        return result;
        
    }
}

LeetCode题目:18. 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]]

以下代码的时间复杂度为 O(n^3)

public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        // 排序
        Arrays.sort(nums);
        
        // 转换为 k Sum 的问题
        return kSum(nums, target, 4, 0, nums.length);
    }

    // 转换为 k Sum 的问题
    private ArrayList<List<Integer>> kSum(int[] nums, int target, int k, int startIndex, int len) {
        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
        
        if(startIndex >= len) {
            return res;
        }
        
        // 2 Sum 问题
        if(k == 2) {
            int low_idx = startIndex;
            int high_idx = len - 1;
            while(low_idx < high_idx) {
                // 找到
                if(nums[low_idx] + nums[high_idx] == target) {
                    List<Integer> temp = new ArrayList<>();
                    temp.add(nums[low_idx]);
                    temp.add(nums[high_idx]);
                    res.add(temp);
                    
                    // 避免重复数字
                    low_idx++;
                    while(low_idx < high_idx && nums[low_idx] == nums[low_idx - 1]) {
                        low_idx++;
                    }
                    
                    // 避免重复数字
                    high_idx--;
                    while(low_idx < high_idx && nums[high_idx] == nums[high_idx + 1]) {
                        high_idx--;
                    }
                }
                else if (nums[low_idx] + nums[high_idx] < target) {
                    low_idx++;
                }
                else {
                    high_idx--;
                }
            }
        }
        
        else {
            for (int i = startIndex; i < len - k + 1; i++) {
                // 递归为 k - 1 Sum 的问题
                ArrayList<List<Integer>> temp = kSum(nums, target - nums[i], k - 1, i + 1, len);
                if(temp != null) {
                    // 聚合 k - 1 Sum 的问题的结果
                    for (List<Integer> t : temp) {
                        t.add(0, nums[i]);
                    }
                    
                    res.addAll(temp);
                }
                
                // 避免重复数字
                while (i < len - k + 1 && nums[i] == nums[i + 1]) {
                    i++;
                }
            }
        }
        
        return res;
    }
}

LeetCode题目:454. 4Sum II
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.

To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.

Example:
Input:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2] 
Output:
2
Explanation:
The two tuples are:
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0

以下代码的时间复杂度为 O(n^2)

class Solution {
    public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
        int result = 0;
        
        int N = A.length;
        
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        
        for(int i = 0; i < N; i++) {
            for(int j = 0; j < N; j++) {
                int sum = A[i] + B[j];
                
                map.put(sum, map.getOrDefault(sum, 0) + 1);
            }
        }
        
        for(int i = 0; i < N; i++) {
            for(int j = 0; j < N; j++) {
                int sum = C[i] + D[j];
                
                result = result + map.getOrDefault(-sum, 0);
            }
        }
        
        return result;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,937评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,503评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,712评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,668评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,677评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,601评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,975评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,637评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,881评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,621评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,710评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,387评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,971评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,947评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,189评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,805评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,449评论 2 342

推荐阅读更多精彩内容