Leetcode--Day13&&Day14

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     }

 
时间: 2024-10-29 11:31:05

Leetcode--Day13&&Day14的相关文章

leetcode -day13 Valid Palindrome &amp; Triangle &amp; Pascal&#39;s Triangle I II

1.  Valid Palindrome Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note:

Leetcode -- Day13

Question 1 Add Binary Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". Firslty I wirte a very direct and kind of brute forch method. Just consider each case of sum 1,

C#操作excel(多种方法比较)

我们在做excel资料的时候,通常有以下方法. 一.导入导出excel常用方法: 1.用查询表的方式查询并show在数据集控件上. public static string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =C:\\08.xls;Extended Properties=Excel 8.0"; public static DataSet ds; protected void Page_Load(obj

Java 学习笔记(2015.7.20~24)

Java 学习笔记(2015.7.20~24) Java Java 学习笔记(2015.7.20~24) 1.StringBuffer与StringBuilder的区别: 2.基本数据类型包装类 3.Date.Calendar.DateFormat等与时间相关的类 1.常用类String 2.正则表达式 3.常用类 StringBuffer 代表可变的字符序列 拆箱与装箱 包装类的应用 匿名内部类 数组 day11 day12 day13 day14 day11 父类中使用public定义的方法

asp.net 操作Excel大全

asp.net 操作Excel大全 转:http://www.cnblogs.com/zhangchenliang/archive/2011/07/21/2112430.html 我们在做excel资料的时候,通常有以下方法. 一.导入导出excel常用方法: 1.用查询表的方式查询并show在数据集控件上.   代码 public static string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =C:\\08.

行转列SQL语句

select top 10 * from schedule_month where years=2016 and months=7 and managerid=45SELECT top 10 cast(years AS varchar) + '-' + RIGHT('0' + CAST(months AS varchar), 2) + '-' + RIGHT('0' + REPLACE(days, 'day', ''), 2) AS trueday, job_title_id, manageri

leetcode -day14 Populating Next Right Pointers in Each Node I II

1.  Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } Populate each next pointer to point to its next right node. If there is no next right node, the

[Java视频笔记]day14

为什么出现集合类? 面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式. 数组和集合类同是容器,有何不同? 数组虽然也可以存储对象,但长度是固定的,集合长度是可变的.数组中可以存储基本对象类型,集合只能存储对象,对象可以不同. 1. add方法的参数类型是Object,以便于接收任意类型对象. 2. 集合中存储的都是对象的引用(地址) 什么是迭代器呢? 其实就是集合的取出元素的方式. 共性方法代码: import java.

[LeetCode] 349 Intersection of Two Arrays &amp; 350 Intersection of Two Arrays II

这两道题都是求两个数组之间的重复元素,因此把它们放在一起. 原题地址: 349 Intersection of Two Arrays :https://leetcode.com/problems/intersection-of-two-arrays/description/ 350 Intersection of Two Arrays II:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/ 题目&解法

LeetCode 442. Find All Duplicates in an Array (在数组中找到所有的重复项)

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements that appear twice in this array. Could you do it without extra space and in O(n) runtime? Example: Input: [4,3,2,7,