futurehau

导航

 

Tips:

1.遇到subArray相关问题,多思考prefix sum

2.2Sum相关问题的两种解法

  hashMap:更加适用于求解结果和下标相关的问题

  sortedArray + twoPoint:更加适用于求解结果和值相关问题。对于closest问题多半是使用 two point

 3.Partition Array 二分 三分

 

Merge Two Sorted Arrays

 1 public int[] mergeSortedArray(int[] A, int[] B) {
 2         // Write your code here
 3         if (A == null) {
 4             return B;
 5         }
 6         if (B == null) {
 7             return A;
 8         }
 9         int m = A.length;
10         int n = B.length;
11         int[] results = new int[m + n];
12         int i = 0;
13         int j = 0;
14         int k = 0;
15         while (i < m && j < n) {
16             if (A[i] < B[j]) {
17                 results[k++] = A[i++];
18             } else {
19                 results[k++] = B[j++];
20             }
21         }
22         while (i < m) {
23             results[k++] = A[i++];
24         }
25         while (j < n) {
26             results[k++] = B[j++];
27         }
28         return results;
29     }
View Code

 

Merge Sorted Array

Given two sorted integer arrays A and B, merge B into A as one sorted array.

 1 public void mergeSortedArray(int[] A, int m, int[] B, int n) {
 2         // write your code here
 3         int k = m + n - 1;
 4         while (m > 0 && n > 0) {
 5             if (A[m - 1] > B[n - 1]) {
 6                 A[k--] = A[--m];
 7             } else {
 8                 A[k--] = B[--n];
 9             }
10         }
11         while (n > 0) {
12             A[k--] = B[--n];
13         }
14     }
View Code

 

Intersection of Two Arrays

Given two arrays, write a function to compute their intersection.

使用两个hash避免使用一个hash的删除操作

 1 public int[] intersection(int[] nums1, int[] nums2) {
 2         // Write your code here
 3         if (nums1 == null || nums2 == null) {
 4             return null;
 5         }
 6         HashSet<Integer> hashSet = new HashSet<Integer>();
 7         HashSet<Integer> resultHash = new HashSet<Integer>();
 8         for (int i = 0; i < nums1.length; i++) {
 9             hashSet.add(nums1[i]);
10         }
11         for (int i = 0; i < nums2.length; i++) {
12             if (hashSet.contains(nums2[i]) && !resultHash.contains(nums2[i])) {
13                 resultHash.add(nums2[i]);
14             }
15         }
16         int[] results = new int[resultHash.size()];
17         int index = 0;
18         for (int i : resultHash) {
19             results[index++] = i;
20         }
21         return results;
22     }
View Code

排序之后再操作--not bug free

 1  public int[] intersection(int[] nums1, int[] nums2) {
 2         // Write your code here
 3         if (nums1 == null || nums2 == null) {
 4             return null;
 5         }
 6         Arrays.sort(nums1);
 7         Arrays.sort(nums2);
 8         int[] results = new int[nums1.length];
 9         int i = 0;
10         int j = 0;
11         int index = 0;
12         while (i < nums1.length && j < nums2.length) {
13             if (nums1[i] == nums2[j]) {
14                 if (index == 0 || results[index - 1] != nums1[i]) {
15                     results[index++] = nums1[i];
16                 }
17                 i++;
18                 j++;
19             } else if (nums1[i] < nums2[j]) {
20                 i++;
21             } else {
22                 j++;
23             }
24         }
25         int[] res = new int[index];
26         for (int k = 0; k < index; k++) {
27             res[k] = results[k];
28         }
29         return res;
30     }
View Code

 

Median of two Sorted Arrays--not bug free

There are two sorted arrays A and B of size m and nrespectively. Find the median of the two sorted arrays.

 1 public double findMedianSortedArrays(int[] A, int[] B) {
 2         // write your code here
 3         if (A == null && B == null) {
 4             return 0;
 5         } 
 6         if (A == null) {
 7             if (B.length % 2 == 0) {
 8                 return (B[B.length / 2 - 1] + B[B.length / 2]) / 2.0;
 9             }
10             else {
11                 return B[B.length / 2];
12             }
13         } 
14         if (B == null) {
15             if (A.length % 2 == 0) {
16                 return (A[A.length / 2 - 1] + A[A.length / 2]) / 2.0;
17             }
18             else {
19                 return A[A.length / 2];
20             }
21         }
22         int m = A.length;
23         int n = B.length;
24         if ((m + n) % 2 == 0) {
25             return (findTopK(A, B, 0, 0, (m + n) / 2) 
26                 + findTopK(A, B, 0, 0, (m + n) / 2 + 1)) / 2.0;
27         } else {
28             return findTopK(A, B, 0, 0, (m + n) / 2 + 1);
29         }
30     }
31     public int findTopK(int[] A, int[] B, int AStart, int BStart,int topK) {
32         if (AStart > A.length  - 1) {
33             return B[BStart + topK - 1];
34         }
35         if (BStart > B.length - 1) {
36             return A[AStart + topK - 1];
37         }
38         if (topK == 1) {
39             return Math.min(A[AStart], B[BStart]);
40         }
41         if (AStart + topK / 2 - 1 > A.length - 1) {
42             return findTopK(A, B, AStart, BStart + topK / 2, topK - topK / 2);
43         }
44         if (BStart + topK / 2 - 1 > B.length - 1) {
45             return findTopK(A, B, AStart + topK / 2, BStart, topK - topK / 2);
46         }
47         if (A[AStart + topK / 2 - 1] < B[BStart + topK / 2 - 1]) {
48             return findTopK(A, B, AStart + topK / 2, BStart, topK - topK / 2);
49         } else {
50             return findTopK(A, B, AStart, BStart + topK / 2, topK - topK / 2);
51         }
52     }
View Code

 

Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 1 public int maxProfit(int[] prices) {
 2         // write your code here
 3         int min = Integer.MAX_VALUE;
 4         int profit = 0;
 5         for (int i = 0; i < prices.length; i++) {
 6             if (prices[i] < min) {
 7                 min = prices[i];
 8             } else {
 9                 profit = Math.max(profit, prices[i] - min);
10             }
11         }
12         return profit;
13     }
View Code

 

Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 

 1 public int maxProfit(int[] prices) {
 2         // write your code here
 3         if (prices == null || prices.length == 0) {
 4             return 0;
 5         }
 6         int profit = 0;
 7         for (int i = 1; i < prices.length; i++) {
 8             if (prices[i] > prices[i - 1]) {
 9                 profit += prices[i] - prices[i - 1];
10             }
11         }
12         return profit;
13     }
View Code

 

Best Time to Buy and Sell Stock III --not bug free

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions

注意Math.max()容易忘记漏写一个参数

 1 public int maxProfit(int[] prices) {
 2         // write your code here
 3         if (prices == null || prices.length == 0) {
 4             return 0;
 5         }
 6         int[] left = new int[prices.length];//profit of one time traction before/at ith day
 7         int[] right = new int[prices.length];//profit of one time traction after/at ith day
 8         int min = prices[0];
 9         for (int i = 1; i < prices.length; i++) {
10             min = Math.min(min, prices[i]);
11             left[i] = Math.max(left[i - 1], prices[i] - min);
12         }
13         int max = prices[prices.length - 1];
14         for (int i = prices.length - 2; i >= 0; i--) {
15             max = Math.max(max, prices[i]);
16             right[i] = Math.max(right[i + 1], max - prices[i]);
17         }
18         int profit = 0;
19         for (int i = 0; i < prices.length; i++) {
20             profit = Math.max(profit, left[i] + right[i]);
21         }
22         return profit;
23     }
View Code

 

 

Best Time to Buy and Sell Stock IV ***

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

 1 public int maxProfit(int k, int[] prices) {
 2         // write your code here
 3         if (prices == null || prices.length < 2) {
 4             return 0;
 5         }
 6         if (k >= prices.length / 2) {
 7             int profit = 0;
 8             for (int i = 1; i < prices.length; i++) {
 9                 if (prices[i] - prices[i - 1] > 0) {
10                     profit += prices[i] - prices[i - 1];
11                 }
12             }
13             return profit;
14         }
15         int n = prices.length;
16         int[][] localMax = new int[n + 1][k + 1];//localMax[i][j]表示前i天最多进行j次交易,并且第i天必须卖出的最大利益
17         int[][] globalMax = new int[n + 1][k + 1];//globalMax[i][j]表示前j天最多进行i次交易的最大利益
18         for (int i = 2; i <= n; i++) {
19             int gainOrLose = prices[i - 1] - prices[i - 2];
20             for (int j = 1; j <= k; j++) {
21                 localMax[i][j] = Math.max(localMax[i - 1][j], globalMax[i - 1][j - 1]) + gainOrLose;
22                 globalMax[i][j] = Math.max(localMax[i][j], globalMax[i - 1][j]);
23             }
24         }
25         return globalMax[n][k];
26     }
View Code

 

Best Time to Buy and Sell Stock with Cooldown ***

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

记:

buy[i]:前 i 天以 buy 作为结尾的最大利益

sell[i]:前 i 天以 sell 作为结尾的最大利益

rest[i]:前 i 天以 rest 作为结尾的最大利益

那么:

现在思考第 i 天,假设这天的价格为price。我们有三种选择:buy sell rest

if we buy, buy[i] = sell[i - 2] - price

if we sell, buy[i] = buy[i - 1]

if we rest, buy[i] = buy[i - 1]

So, buy[i] = Math.max(buy[i - 1], sell[i - 2] - price)

同样的道理:

if we buy, sell[i] = sell[i - 1]

if we sell, sell[i] = buy[i - 1] + price

if we rest, sell[i] = sell[i - 1]

So,sell[i] = Math.max(sell[i - 1], buy[i - 1] + price)

所以使用动态规划来求解,考虑到buy 和 sell 都只和他们前边的一个/两个有关,所以可以降维,空间复杂度为O(1)

 1 //buy[i] = Math.max(buy[i - 1], sell[i - 2] - price)
 2     //sell[i] = Math.max(sell[i - 1], buy[i - 1] + price)
 3     public int maxProfit(int[] prices) {
 4         int sell = 0;
 5         int prevSell = 0;
 6         int buy = Integer.MIN_VALUE;
 7         int prevBuy = Integer.MIN_VALUE;
 8         for (int price : prices) {
 9             prevBuy = buy;
10             buy = Math.max(prevBuy, prevSell - price);
11             prevSell = sell;
12             sell = Math.max(prevSell, prevBuy + price);
13         }
14         return sell;
15     }
View Code

 

Maximum Subarray --not bug free

其实就相当于我得到pfefixArray数组之后,求只交易一次的最大利益。

 1 public int maxSubArray(int[] nums) {
 2         // write your code
 3         if (nums == null || nums.length == 0) {
 4             return 0;
 5         }
 6         int maxSum = Integer.MIN_VALUE;
 7         int prefixSum = 0;
 8         for (int i = 0; i < nums.length; i++) {
 9             maxSum = Math.max(maxSum, nums[i] + prefixSum);
10             prefixSum += nums[i];
11             if (prefixSum < 0) {
12                 prefixSum = 0;
13             }
14         }
15         return maxSum;
16     }
View Code

 

Maximum SubarrayII--not bug free

Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.

 注意min的初始化,不能初始化为Integer.MAX_VALUE

 1 public int maxTwoSubArrays(ArrayList<Integer> nums) {
 2         // write your code
 3         if (nums == null || nums.size() == 0) {
 4             return 0;
 5         }
 6         int size = nums.size();
 7         int[] left = new int[size];
 8         int[] right = new int[size];
 9         int sum = 0;
10         int minSum = 0;
11         int max = Integer.MIN_VALUE;
12         for (int i = 0; i < size; i++) {
13             sum += nums.get(i);
14             max = Math.max(max, sum - minSum);
15             minSum = Math.min(minSum, sum);
16             left[i] = max;
17         }
18         sum = 0;
19         minSum = 0;
20         max = Integer.MIN_VALUE;
21         for (int i = size - 1; i >= 0; i--) {
22             sum += nums.get(i);
23             max = Math.max(max, sum - minSum);
24             minSum = Math.min(minSum, sum);
25             right[i] = max;
26         }
27         max = Integer.MIN_VALUE;
28         for (int i = 0; i < size - 1; i++) {
29             max = Math.max(max, left[i] + right[i + 1]);
30         }
31         return max;
32     }
View Code

 

 Maximum Subarray III ***** --not bug free

Given an array of integers and a number k, find knon-overlapping subarrays which have the largest sum.

The number in each subarray should be contiguous.

Return the largest sum.

方法一:

f[i][j]标志以位置j结尾的子数组,i组的最大和,其中最后一个分组必须以j位置作为结束。那么如果 i > j + 1,f[i][j] = 0;可以先求得f[i][i - 1]再求得f[1][j],再一次求得f[i][j].

f[i][j] = max(f[i][j - 1] + nums[j], f[i - 1][m], nums[m]),也即 j 单独作为一个分组/ j和前边分组结合。这样最后可以求得f[k][j],由于划分为k组的最大可能以任何一个作为结尾,因为对这些值求最大即可。

 1  public int maxSubArray(int[] nums, int k) {
 2         // write your code here
 3         if (nums == null || nums.length < k) {
 4             return 0;
 5         }
 6         int n = nums.length;
 7         int[][] f = new int[k + 1][n];
 8         int sum = 0;
 9         for (int i = 1; i <= k; i++) {
10             sum += nums[i - 1];
11             f[i][i - 1] = sum;
12         }
13         for (int i = 1; i < n; i++) {
14             f[1][i] = Math.max(f[1][i - 1] + nums[i], nums[i]);
15         }
16         for (int i = 2; i <= k; i++) {
17             for (int j = i; j < n; j++) {
18                 int curMax = f[i][j - 1] + nums[j];
19                 for (int m = i - 2; m < j; m++) {
20                     curMax = Math.max(curMax, f[i - 1][m] + nums[j]);
21                 }
22                 f[i][j] = curMax;
23             }
24         }
25         int max = Integer.MIN_VALUE;
26         for (int i = k - 1; i < n; i++) {
27             max = Math.max(max, f[k][i]);
28         }
29         return max;
30     }
View Code

方法二:划分类DP *****

localMax[i][j]表示前j个元素的子数组的 i 个子数组的Maximum Subarray,并且以第j个元素作为结尾

globalMax[i][j]表示前j个元素的子数组的 i 个子数组的Maximal Subarray。

 1 public int maxSubArray(int[] nums, int k) {
 2         // write your code here
 3         if (nums == null || nums.length < k) {
 4             return 0;
 5         }
 6         int n = nums.length;
 7         int[][] localMax = new int[k + 1][n + 1];
 8         int[][] globalMax = new int[k + 1][n + 1];
 9         for (int i = 1; i <= k; i++) {
10             localMax[i][i - 1] = Integer.MIN_VALUE;
11             for (int j = i; j <= n; j++) {
12                 localMax[i][j] = Math.max(localMax[i][j - 1], 
13                                  globalMax[i - 1][j - 1]) + nums[j - 1];
14                 if (i == j) {
15                     globalMax[i][j] = localMax[i][j];
16                 } else {
17                     globalMax[i][j] = Math.max(localMax[i][j], globalMax[i][j - 1]);
18                 }
19             }
20         }
21         return globalMax[k][n];
22     }
View Code

 

Minimum Subarray

 1 public int minSubArray(ArrayList<Integer> nums) {
 2         // write your code
 3         if (nums == null || nums.size() == 0) {
 4             return 0;
 5         }
 6         int max = Integer.MIN_VALUE;
 7         int sum = 0;
 8         for (int i = 0; i < nums.size(); i++) {
 9             sum -= nums.get(i);
10             max = Math.max(max, sum);
11             if (sum < 0) {
12                 sum = 0;
13             }
14         }
15         return -max;
16     }
View Code

 

Maximum Subarray Difference --not bug free

Given an array with integers.

Find two non-overlapping subarrays A and B, which|SUM(A) - SUM(B)| is the largest.

Return the largest difference.

 1  public int maxDiffSubArrays(int[] nums) {
 2         // write your code here
 3         if (nums == null || nums.length == 0) {
 4             return 0;
 5         }
 6         
 7         int[] leftMax = getLeft(nums, true);
 8         int[] leftMin = getLeft(nums, false);
 9         int[] rightMax = getRight(nums, true);
10         int[] rightMin = getRight(nums,false);
11        
12         int max = Integer.MIN_VALUE;
13         max = Math.max(max, getMaxFromLeft(leftMax, rightMin));
14         max = Math.max(max, getMaxFromRight(rightMax, leftMin));
15         return max;
16     }
17     
18     public int[] getLeft(int[] nums, boolean flag) {
19         int n = nums.length;
20         int[] left = new int[n];
21         int sum = 0;
22         int min = 0;
23         int max = Integer.MIN_VALUE;
24         for (int i = 0; i < n; i++) {
25             if (flag) {
26                 sum += nums[i];
27             } else {
28                 sum -= nums[i];
29             }
30             max = Math.max(max, sum - min);
31             min = Math.min(min, sum);
32             if (flag) {
33                 left[i] = max;
34             } else {
35                 left[i] = -max;
36             }
37         }
38         return left;
39     }
40     
41     public int[] getRight(int[] nums, boolean flag) {
42         int n = nums.length;
43         int[] right = new int[n];
44         int sum = 0;
45         int min = 0;
46         int max = Integer.MIN_VALUE;
47         for (int i = n - 1; i >= 0; i--) {
48             if (flag) {
49                 sum += nums[i];
50             } else {
51                 sum -= nums[i];
52             }
53             
54             max = Math.max(max, sum - min);
55             min = Math.min(min, sum);
56             if (flag) {
57                 right[i] = max;
58             } else {
59                 right[i] = -max;
60             }
61         }
62         return right;
63     }
64     
65     public int getMaxFromLeft(int[] left, int[] right) {
66         int max = Integer.MIN_VALUE;
67         for (int i = 0; i < left.length - 1; i++) {
68             max = Math.max(max, left[i] - right[i + 1]);
69         }
70         return max;
71     }
72     
73     public int getMaxFromRight(int[] right, int[] left) {
74         int max = Integer.MIN_VALUE;
75         for (int i = right.length - 1; i > 0; i--) {
76             max = Math.max(max, right[i] - left[i - 1]);
77         }
78         return max;
79     }
View Code

Subarray Sum --not bug free

Given an integer array, find a subarray where the sum of numbers is zero. Your code should return the index of the first number and the index of the last number.

注意开始map中放入(0 -> -1)

 1  public ArrayList<Integer> subarraySum(int[] nums) {
 2         // write your code here
 3         ArrayList<Integer> result = new ArrayList<Integer>();
 4         if (nums == null || nums.length == 0) {
 5             return result;
 6         }
 7         HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 8         map.put(0, - 1);//Attention!
 9         int sum = 0;
10         for (int i = 0; i < nums.length; i++) {
11             sum += nums[i];
12             if (map.containsKey(sum)) {
13                 result.add(map.get(sum) + 1);
14                 result.add(i);
15                 return result;
16             } else {
17                 map.put(sum, i);
18             }
19         }
20         return result;
21     }
View Code

 

Subarray Sum Closest --not bug free

Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.

 1 public int[] subarraySumClosest(int[] nums) {
 2         // write your code here
 3         int[] result = new int[2];
 4         if (nums == null || nums.length == 0) {
 5             return result;
 6         }
 7         if (nums.length == 1) {
 8             result[0] = 0;
 9             result[1] = 0;
10             return result;
11         }
12         Pair[] sums = new Pair[nums.length + 1];
13         sums[nums.length] = new Pair(0, -1);
14         int prev = 0;
15         for (int i = 0; i < nums.length; i++) {
16             prev += nums[i];
17             sums[i] = new Pair(prev, i);
18         }
19         Arrays.sort(sums,new Comparator<Pair>() {
20             public int compare(Pair a, Pair b) {
21                 return a.sum - b.sum;
22             }
23         });
24         int diff = Integer.MAX_VALUE;
25         for (int i = 1; i < sums.length; i++) {
26             if (sums[i].sum - sums[i - 1].sum < diff) {
27                 diff = sums[i].sum - sums[i - 1].sum;
28                 result[0] = sums[i].index;
29                 result[1] = sums[i - 1].index;
30             }
31         }
32         Arrays.sort(result);
33         result[0] = result[0] + 1;
34         return result;
35     }
36 }
37 class Pair {
38     int sum;
39     int index;
40     public Pair(int s, int k) {
41         sum = s;
42         index = k;
43     }
View Code

 

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.

 1  public int[] twoSum(int[] numbers, int target) {
 2         // write your code here
 3         int[] result = new int[2];
 4         if (numbers == null || numbers.length < 2) {
 5             return result;
 6         }
 7         HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
 8         for (int i = 0; i < numbers.length; i++) {
 9             if (hashMap.containsKey(target - numbers[i])) {
10                 result[0] = hashMap.get(target - numbers[i]) + 1;
11                 result[1] = i + 1;
12                 return result;
13             } else {
14                 hashMap.put(numbers[i], i);
15             }
16         }
17         return result;
18     }
View Code

 

Two Sum Closest --not bug free

Given an array nums of n integers, find two integers in nums such that the sum is closest to a given number, target.

Return the difference between the sum of the two integers and the target.

 1 public int twoSumCloset(int[] nums, int target) {
 2         // Write your code here
 3         if (nums == null || nums.length < 2) {
 4             return Integer.MAX_VALUE;
 5         }
 6         Arrays.sort(nums);
 7         int left = 0;
 8         int right = nums.length - 1;
 9         int diff = Integer.MAX_VALUE;
10         while (left < right) {
11             int tmp = nums[left] + nums[right];
12             if (tmp < target) {
13                 if (target - tmp < diff) {
14                     diff = target - tmp;
15                 }
16                 left++;
17             } else if (tmp > target) {
18                 if (tmp - target < diff) {
19                     diff = tmp - target;
20                 }
21                 right--;
22             } else {
23                 return 0;
24             }
25         }
26         return diff;
27     }
View Code

 

3Sum --not bug free

变量容易写习惯了导致错误。找到一个满足条件的之后。left 和 right的变化容易导致bug,不仅仅是left++, right--就可以了。 

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.

 1  public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
 2         // write your code here
 3         ArrayList<ArrayList<Integer>> results = new ArrayList<>();
 4         if (numbers == null || numbers.length < 3) {
 5             return results;
 6         }
 7         int n = numbers.length;
 8         Arrays.sort(numbers);
 9         for (int i = 0; i < n - 2; i++) {
10             if (i > 0 && numbers[i] == numbers[i - 1]) {
11                 continue;
12             }
13             int left = i + 1;
14             int right = n - 1;
15             while (left < right) {
16                 int temp = numbers[i] + numbers[left] + numbers[right];
17                 if (temp < 0) {
18                     left++;
19                 } else if (temp > 0) {
20                     right--;
21                 } else {
22                      ArrayList<Integer> cur = new ArrayList<Integer>();
23                      cur.add(numbers[i]);
24                      cur.add(numbers[left]);
25                      cur.add(numbers[right]);
26                      results.add(cur);
27                      int temp1 = numbers[left];
28                      int temp2 = numbers[right];
29                      while (++left < right && numbers[left] == temp1) {}
30                      while (--right > left && numbers[right] == temp2) {}
31                 }
32             }
33         }
34         return results;
35     }
View Code

 

3Sum Closest --not bug free

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.

bug的几个原因:

1.漏写了返回,实在不应该。

2.看清题目意思,返回的是sum 不是diff

3.left++ right-- 忘记了

4.忘记了先排序

要想一次bug free这些简单题还应该更注意细节啊

 1 public int threeSumClosest(int[] numbers, int target) {
 2         // write your code here
 3         if (numbers == null || numbers.length < 3) {
 4             return -1;
 5         }
 6         Arrays.sort(numbers);
 7         int n = numbers.length;
 8         int result = numbers[0] + numbers[1] +numbers[2];
 9         for (int i = 0; i < n - 2; i++) {
10             if (i != 0 && numbers[i] == numbers[i - 1]) {
11                 continue;
12             }
13             int left = i + 1;
14             int right = n - 1;
15             while (left < right) {
16                 int temp = numbers[i] + numbers[left] + numbers[right];
17                 if (Math.abs(temp - target) < Math.abs(result - target)) {
18                     result = temp;
19                 }
20                 if (temp < target) {
21                     left++;
22                 } else if (temp > target) {
23                     right--;
24                 } else {
25                     return target;
26                 }
27             }
28         }
29         return result;
30     }
View Code

 

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.

 1  public ArrayList<ArrayList<Integer>> fourSum(int[] numbers, int target) {
 2         /* your code */
 3         ArrayList<ArrayList<Integer>> results = new ArrayList<>();
 4         if (numbers == null || numbers.length < 4) {
 5             return results;
 6         }
 7         Arrays.sort(numbers);
 8         int n = numbers.length;
 9         for (int i = 0; i < n - 3; i++) {
10             if (i != 0 && numbers[i] == numbers[i - 1]) {
11                 continue;
12             }
13             for (int j = i + 1; j < n - 2; j++) {
14                 if (j != i + 1 && numbers[j] == numbers[j - 1]) {
15                     continue;
16                 }
17                 int left = j + 1;
18                 int right = n - 1;
19                 while (left < right) {
20                     int temp = numbers[i] + numbers[j] + numbers[left] + numbers[right];
21                     if (temp < target) {
22                         left++;
23                     } else if (temp > target) {
24                         right--;
25                     } else {
26                         ArrayList<Integer> cur = new ArrayList<>();
27                         cur.add(numbers[i]);
28                         cur.add(numbers[j]);
29                         cur.add(numbers[left]);
30                         cur.add(numbers[right]);
31                         results.add(cur);
32                         int temp1 = numbers[left];
33                         int temp2 = numbers[right];
34                         while (left < right && numbers[left] == temp1) {
35                             left++;
36                         }
37                         while (left < right && numbers[right] == temp2) {
38                             right--;
39                         }
40                     }
41                 }
42             }
43         }
44         return results;
45     }
View Code

 

 

4Sum II --something else

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.

自己只写出了hash的解法,复杂度O(n^2)。再次看到的时候去看看有没有bs的解法。

 1 public int fourSumCount(int[] A, int[] B, int[] C, int[] D) {
 2         HashMap<Integer, Integer> map12 = new HashMap<Integer, Integer>();
 3         twoCombination(A, B, map12);
 4         int res = 0;
 5         for (int num1 : C) {
 6            for (int num2 : D) {
 7                res += map12.getOrDefault(-num1 - num2, 0);
 8            }
 9         }
10         return res;
11     }
12     public void twoCombination(int[] nums1, int[] nums2, HashMap<Integer, Integer> map) {
13         int sum = 0;
14         for (int i = 0; i < nums1.length; i++) {
15            for (int j = 0; j < nums2.length; j++) {
16                sum = nums1[i] + nums2[j];
17                map.put(sum, map.getOrDefault(sum, 0) + 1);
18            }
19         }
20     }
View Code

 

 

Partition Array--not bug free

边界问题没有处理好

Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:

  • All elements < k are moved to the left
  • All elements >= k are moved to the right

Return the partitioning index, i.e the first index i nums[i] >= k.

public int partitionArray(int[] nums, int k) {
     //write your code here
     if (nums == null || nums.length == 0) {
         return 0;
     }
     int n = nums.length;
     int left = 0;
     int right = n - 1;
     while (left <= right) {
         while (left <= right && nums[left] < k) {
             left++;
         }
         while (right >= left && nums[right] >= k){
             right--;
         }
         if (left < right) {
             swap(nums, left, right);
         }
     }
     return left;
 }
 public void swap(int[] nums, int i, int j) {
     int temp = nums[i];
     nums[i] = nums[j];
     nums[j] = temp;
 }
View Code

 

 Sort Letters by Case--not bug free

Given a string which contains only letters. Sort it by lower case first and upper case second.

 1 public void sortLetters(char[] chars) {
 2  //write your code here
 3     if (chars == null || chars.length == 0) {
 4         return ;
 5     }
 6     int left = 0;
 7     int right = chars.length - 1;
 8     while (left < right) {
 9         if (chars[left] - 'a' >= 0) {
10             left++;
11         } else {
12             swap(chars, left, right);
13             right--;
14         }
15     }
16  }
17  public void swap(char[] chars, int i, int j) {
18      char temp = chars[i];
19      chars[i] = chars[j];
20      chars[j] = temp;
21  }
View Code

 

Sort Colors--not bug free

对于出现"2"的情况之前处理错误

Given an array with n objects colored redwhite or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 01, and 2 to represent the color red, white, and blue respectively.

 1  public void sortColors(int[] nums) {
 2         // write your code here
 3         if (nums == null || nums.length == 0) {
 4             return ;
 5         }
 6         
 7         int left = 0;
 8         int right = nums.length - 1;
 9         int index = 0;
10         while (index <= right) {
11             if (nums[index] == 1) {
12                 index++;
13             } else if (nums[index] == 0) {
14                 swap(nums, left, index);
15                 left++;
16                 index++;
17             } else {
18                 swap(nums, right, index);
19                 right--;
20             }
21         }
22     }
23     public void swap(int[] nums, int i, int j) {
24         int temp = nums[i];
25         nums[i] = nums[j];
26         nums[j] = temp;
27     }
View Code

 

Sort Colors II

Given an array of n objects with k different colors (numbered from 1 to k), sort them so that objects of the same color are adjacent, with the colors in the order 1, 2, ... k.

递归。复杂度O(k^2)

 1 public void sortColors2(int[] colors, int k) {
 2         // write your code here
 3         if (colors == null || colors.length == 0) {
 4             return ;
 5         }
 6         sortColorsHelper(colors, 0, colors.length - 1, 1, k);
 7     }
 8     
 9     public void sortColorsHelper(int[] colors, int left, int right, int num1, int num2) {
10         if (num1 >= num2 || left >= right) {
11             return ;
12         }
13         int index = left;
14         while (index <= right) {
15             if (colors[index] == num1) {
16                 swap(colors, index, left);
17                 left++;
18                 index++;
19             } else if (colors[index] == num2) {
20                 swap(colors, index, right);
21                 right--;
22             } else {
23                 index++;
24             }
25         }
26         sortColorsHelper(colors, left, right, num1 + 1, num2 - 1);
27     }
28     
29     public void swap(int[] colors, int i, int j) {
30         int temp = colors[i];
31         colors[i] = colors[j];
32         colors[j] = temp;
33     }
View Code

 

Interleaving Positive and Negative Numbers

Given an array with positive and negative integers. Re-range it to interleaving with positive and negative integers.

 1 public void rerange(int[] A) {
 2         // write your code here
 3         if (A == null || A.length < 3) {
 4             return ;
 5         }
 6         int left = 0;
 7         int right = A.length - 1;
 8         while (left <= right) {
 9             if (A[left] < 0) {
10                 left++;
11             } else {
12                 swap(A, left, right);
13                 right--;
14             }
15         }
16         int divide = left;
17         while (right >= 0 && left < A.length) {
18                 swap(A, left, right);
19                 left += 2;
20                 right -= 2;
21         }
22         if (A[0] * A[1] > 0) {
23             int temp = A[0];
24             for (int i = 0; i < A.length - 1; i++) {
25                 A[i] = A[i + 1];
26             }
27             A[A.length - 1] = temp;
28         } else if (A[A.length - 1] * A[A.length - 2] > 0) {
29             int temp = A[A.length - 1];
30             for (int i = A.length - 1; i > 0; i--) {
31                 A[i] = A[i - 1];
32             }
33             A[0] = temp;
34         }
35    }
36    public void swap(int[] A, int i, int j) {
37        int temp = A[i];
38        A[i] = A[j];
39        A[j] = temp;
40    }
View Code

 

Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

方法一:记录第一个为负数的段,之后前缀乘积为负数的时候直接除以这个就行

 1 public int maxProduct(int[] nums) {
 2         if (nums == null || nums.length == 0) {
 3             return 0;
 4         }
 5         int max = Integer.MIN_VALUE;
 6         int prevNeg = 1;
 7         int product = 1;
 8         for (int i = 0; i < nums.length; i++) {
 9             if (nums[i] == 0) {
10                 prevNeg = 1;
11                 product = 1;
12                 max = Math.max(max, 0);
13             } else {
14                 product *= nums[i];
15                 if (product > 0) {
16                     max = Math.max(max, product);
17                 } else {
18                     max = Math.max(max, product / prevNeg);
19                     if (prevNeg == 1) {
20                         prevNeg = product;
21                     }
22                 }
23             }
24         }
25         return max;
26     }
View Code

 

方法二:从开始到结束遍历一遍,从结束到开始遍历一遍即可。因为没有0的最大一定是开始于开始或者结束于结束

 1 public int maxProduct(int[] nums) {
 2         // write your code here
 3         if (nums == null || nums.length == 0) {
 4             return 0;
 5         }
 6         int max = Integer.MIN_VALUE;
 7         int product = 1;
 8         for (int i = 0; i < nums.length; i++) {
 9             if (nums[i] == 0) {
10                 product = 1;
11             } else {
12                 product *= nums[i];
13                 max = Math.max(max, product);
14             }
15         }
16         product = 1;
17         for (int i = nums.length - 1; i >= 0; i--) {
18             if (nums[i] == 0) {
19                 product = 1;
20             } else {
21                 product *= nums[i];
22                 max = Math.max(max, product);
23             }
24         }
25         return max;
26     }
View Code

 

posted on 2016-10-07 00:06  futurehau  阅读(316)  评论(0编辑  收藏  举报