Leet Code OJ 15. 3Sum[Difficulty: Medium]

题目:

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:

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)

翻译:

给定一个数组S,它包含n个整数,它是否存在3个元素a,b,c,满足a+b+c=0?找出所有满足条件的元素数组。

提示:a,b,c三个元素必须是升序排列(也就是满足a ≤ b ≤ c),最终的结果不能包含重复的元素数组。例如给定S为{-1 0 1 2 -1 -4},返回结果是(-1, 0, 1)和(-1, -1, 2)。

分析:

最容易想到的方法就是3重循环遍历所有可能的元素,进行判断是否等于0。下面的方案作了一些改进:

1. 对数组进行排序,跳过肯定会大于0的结果

2. 借助map避免第三层遍历

3. 由于做了排序,所以可以较为容易的跳过重复的结果

代码(Java版):

public class Solution {
    public List <List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        //nums先进行排序
        Arrays.sort(nums);
        Map<Integer, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.get(num) == null) {
                List<Integer> subscripts = new ArrayList<>();
                subscripts.add(i);
                map.put(num, subscripts);
            } else {
                map.get(num).add(i);
            }
        }
        for (int i = 0; i <= nums.length - 3; i++) {
            if (nums[i] > 0) {
                break;
            }
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j <= nums.length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int finalNum = -nums[i] - nums[j];
                if (finalNum < nums[j]) {
                    break;
                }
                List<Integer> subscripts = map.get(finalNum);
                if (subscripts == null) {
                    continue;
                }
                for (Integer subscript : subscripts) {
                    if (subscript != j && subscript != i) {
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[subscript]);
                        res.add(list);
                        break;
                    }
                }
            }
        }
        return res;
    }
}
时间: 2024-11-08 06:35:36

Leet Code OJ 15. 3Sum[Difficulty: Medium]的相关文章

Leet Code OJ 119. Pascal&#39;s Triangle II [Difficulty: Easy]

题目: Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. Note: Could you optimize your algorithm to use only O(k) extra space? 翻译: 给定一个下标k,返回第k行的杨辉三角. 例如给定k=3,返回[1,3,3,1]. 提示:你可以优化你的算法,让它只使用O(k)的额

Leet Code OJ 118. Pascal&#39;s Triangle [Difficulty: Easy]

题目: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 翻译: 给定一个数numRows,产生前numRows行的杨辉三角(即贾宪三角形.帕斯卡三角形). 分析: 除了每行首尾是1以外,其他元素均可由上行推出,本方案采用lastLine保存上行数

Leet Code OJ 338. Counting Bits [Difficulty: Medium]

题目: Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example: For num = 5 you should return [0,1,1,2,1,2]. Follow up: It is v

Leet Code OJ 91. Decode Ways [Difficulty: Medium]

题目: A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given an encoded message containing digits, determine the total number of ways to decode it. For example, Given enc

Leet Code OJ 107. Binary Tree Level Order Traversal II [Difficulty: Easy]

题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree {3,9,20,#,#,15,7}, return its bottom-up level order traversal as: [ [

Leet Code OJ 1. Two Sum [Difficulty: Easy]

题目: 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. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1]

Leet Code OJ 102. Binary Tree Level Order Traversal [Difficulty: Easy]

题目: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree {3,9,20,#,#,15,7}, return its level order traversal as: [ [3], [9,20], [15,7] ] 翻译: 给定一个二叉树,返回它的节

Leet Code OJ 189. Rotate Array [Difficulty: Easy]

题目: Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4]. Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve thi

Leet Code OJ 237. Delete Node in a Linked List [Difficulty: Easy]

题目: Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -