transformArray(int[] arr) {
9 | int[] ans = new int[arr.length];
10 | while (!Arrays.equals(ans, arr)) {
11 | ans = arr.clone();
12 | for (int i = 1; i < arr.length - 1; ++i) {
13 | if (ans[i - 1] < ans[i] && ans[i] > ans[i + 1]) {
14 | --arr[i];
15 | } else if (ans[i - 1] > ans[i] && ans[i] < ans[i + 1]) {
16 | ++arr[i];
17 | }
18 | }
19 | }
20 | return Arrays.stream(ans).boxed().collect(Collectors.toList());
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/Base7.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 |
3 | /**
4 | * Given an integer, return its base 7 string representation.
5 | *
6 | * Example 1:
7 | * Input: 100
8 | * Output: "202"
9 | * Example 2:
10 | * Input: -7
11 | * Output: "-10"
12 | */
13 | public class Base7 {
14 | public String convertToBase7(int num) {
15 | String res = "";
16 | boolean flag = false;
17 | if (num < 0) {
18 | flag = true;
19 | num = -num;
20 | }
21 | while (num >= 7) {
22 | int residue = num - 7 * (num / 7);
23 | num = num / 7;
24 | res = residue + res;
25 | }
26 | res = num + res;
27 | if (flag)
28 | res = "-" + res;
29 | return res;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BeautifulArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 |
3 | /**
4 | * For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:
5 | *
6 | * For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
7 | *
8 | * Given N, return any beautiful array A. (It is guaranteed that one exists.)
9 | *
10 | *
11 | *
12 | * Example 1:
13 | *
14 | * Input: 4
15 | * Output: [2,1,4,3]
16 | * Example 2:
17 | *
18 | * Input: 5
19 | * Output: [3,1,2,5,4]
20 | */
21 | public class BeautifulArray {
22 | public int[] beautifulArray(int N) {
23 | return null;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BestTimetoBuyandSellStockwithCooldown.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 |
3 | /**
4 | * Say you have an array for which the ith element is the price of a given stock on day i.
5 |
6 | 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:
7 |
8 | You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
9 | After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
10 | Example:
11 |
12 | prices = [1, 2, 3, 0, 2]
13 | maxProfit = 3
14 | transactions = [buy, sell, cooldown, buy, sell]
15 | */
16 | public class BestTimetoBuyandSellStockwithCooldown {
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BinaryGap2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 |
3 | /**
4 | * Created by gaohan on 8/4/18.
5 | * Complexity Analysis
6 |
7 | Time Complexity: O(\log N)O(logN). Note that \log NlogN is the number of digits in the binary representation of NN.
8 |
9 | Space Complexity: O(1)O(1).
10 | */
11 | public class BinaryGap2 {
12 | public int binaryGap(int N) {
13 | int last = -1, ans = 0;
14 | for (int i = 0; i < 32; ++i)
15 | if (((N >> i) & 1) > 0) {
16 | if (last >= 0)
17 | ans = Math.max(ans, i - last);
18 | last = i;
19 | }
20 |
21 | return ans;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BinaryTreeLongestConsecutiveSequence.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | public class BinaryTreeLongestConsecutiveSequence {
6 | public int longestConsecutive(TreeNode root) {
7 | return 0;
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BinaryTreeUpsideDown.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gaohannk/Leetcode/e0e111835b0fae2e27d80ac9e012f5052c6bd1a2/src/leetcode/algo/b/BinaryTreeUpsideDown.png
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BitwiseANDofNumbersRange3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 | /* Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
3 | * For example, given the range [5, 7], you should return 4.
4 | */
5 | public class BitwiseANDofNumbersRange3 {
6 | public int rangeBitwiseAnd(int m, int n) {
7 | int r = Integer.MAX_VALUE;
8 | while ((m & r) != (n & r))
9 | r = r << 1;
10 | return n & r;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BitwiseORsofSubarrays.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 |
3 | import java.util.HashSet;
4 | import java.util.Set;
5 |
6 | public class BitwiseORsofSubarrays {
7 | public int subarrayBitwiseORs(int[] A) {
8 | Set ans = new HashSet();
9 | Set cur = new HashSet();
10 | cur.add(0);
11 | for (int x : A) {
12 | Set cur2 = new HashSet();
13 | for (int y : cur)
14 | cur2.add(x | y);
15 | cur2.add(x);
16 | cur = cur2;
17 | ans.addAll(cur);
18 | }
19 |
20 | return ans.size();
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/b/BullsandCows2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.b;
2 |
3 | public class BullsandCows2 {
4 | public String getHint(String secret, String guess) {
5 | int[] amap = new int[10];
6 | int[] bmap = new int[10];
7 | int atimes = 0, btimes = 0;
8 | for (int i = 0; i < guess.length(); i++) {
9 | if (secret.charAt(i) == guess.charAt(i)) {
10 | atimes++;
11 | } else {
12 | amap[secret.charAt(i) - '0']++;
13 | bmap[guess.charAt(i) - '0']++;
14 | }
15 | }
16 | for (int i = 0; i < 10; i++) {
17 | btimes += Math.min(amap[i], bmap[i]);
18 | }
19 | return atimes + "A" + btimes + "B";
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CarFleet.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class CarFleet {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CatandMouse.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class CatandMouse {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CheckIfaNumberIsMajorityElementinaSortedArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class CheckIfaNumberIsMajorityElementinaSortedArray {
4 | public boolean isMajorityElement(int[] nums, int target) {
5 | int count = 0;
6 |
7 | for (int i : nums) {
8 | if (i == target) {
9 | count++;
10 | if (count > nums.length / 2) {
11 | //is majority
12 | return true;
13 | }
14 | }
15 | }
16 | return false;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CheckIfaNumberIsMajorityElementinaSortedArray2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class CheckIfaNumberIsMajorityElementinaSortedArray2 {
4 | public boolean isMajorityElement(int[] nums, int target) {
5 | return nums[nums.length/2] == target && nums[nums.length/2-1] == target;
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ClimbingStairs2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 | /* You are climbing a stair case. It takes n steps to reach to the top.
3 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
4 | */
5 | // DP Time O(n) Space O(n)
6 | public class ClimbingStairs2 {
7 | public int climbStairs(int n) {
8 | if (n == 1)
9 | return 1;
10 | int[] dp = new int[n + 1];
11 | dp[0] = 1;
12 | dp[1] = 1;
13 | for (int i = 2; i <= n; i++) {
14 | dp[i] = dp[i - 1] + dp[i - 2];
15 | }
16 | return dp[n];
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ClosestBinarySearchTreeValue2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | import java.util.Stack;
6 |
7 | public class ClosestBinarySearchTreeValue2 {
8 | public int closestValue(TreeNode root, double target) {
9 | Stack stk = new Stack();
10 | TreeNode cur = root;
11 | TreeNode pre = null;
12 | while (!stk.isEmpty() || cur != null) {
13 | if (cur != null) {
14 | stk.push(cur);
15 | cur = cur.left;
16 | } else {
17 | TreeNode node = stk.pop();
18 | if (target < node.val) {
19 | return pre != null && Math.abs(node.val - target) > Math.abs(pre.val - target) ? pre.val : node.val;
20 | }
21 | pre = node;
22 | cur = node.right;
23 | }
24 | }
25 | return pre.val;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ClumsyFactorial.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class ClumsyFactorial {
4 | public int clumsy(int N) {
5 | if (N == 1) {return 1;}
6 | if (N == 2) {return 2;}
7 | if (N == 3) {return 6;}
8 | if (N == 4) {return 7;}
9 |
10 | int res = N + 1;
11 |
12 | int remain = N - 3;
13 |
14 | if (remain % 4 == 0) {res -= 2;}
15 | if (remain % 4 == 2 || (remain % 4 == 3)) {res += 1;}
16 |
17 | return res;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CoinChangeII2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 | // TLE DFS method
3 | public class CoinChangeII2 {
4 | public int change(int amount, int[] coins) {
5 | int res[] = new int[1];
6 | helper(coins, res, 0, amount, coins.length-1);
7 | return res[0];
8 | }
9 |
10 | public void helper(int[] coins, int[] res, int sum, int amount, int start) {
11 | if (sum > amount) {
12 | return;
13 | }
14 | if (sum == amount) {
15 | res[0]++;
16 | //System.out.println(res[0]);
17 | return;
18 | }
19 | for (int i = start; i >= 0; i--) {
20 | sum += coins[i];
21 | helper(coins, res, sum, amount, i);
22 | sum -= coins[i];
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/Combinations2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 | /* Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
3 | * For example,
4 | * If n = 4 and k = 2, a solution is:
5 | * [
6 | * [2,4],
7 | * [3,4],
8 | * [2,3],
9 | * [1,2],
10 | * [1,3],
11 | * [1,4],
12 | * ]
13 | */
14 | public class Combinations2 {
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ConnectingCitiesWithMinimumCost.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class ConnectingCitiesWithMinimumCost {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ConsecutiveNumberSum3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | /**
4 | * Created by gaohan on 5/31/18.
5 | */
6 | public class ConsecutiveNumberSum3 {
7 | public int consecutiveNumbersSum(int N) {
8 | int res = 1, limit = (int) Math.sqrt(N * 2);//如果N可以分成i个连续数字,那么N>=(i+1)*i/2,相应的,i<=sqrt(N*2)
9 | for (int i = 2; i <= limit; i++) {
10 | if (i % 2 == 0 && (2 * N) % i == 0 && ((2 * N) / i) % 2 == 1)
11 | res++;//如果i为偶数,N必须要能被i/2整除,且除出来的数要为奇数
12 | if (i % 2 == 1 && N % i == 0)
13 | res++;//如果i为奇数,那么,只要N能被i整除,就OK
14 | }
15 | return res;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ConsecutiveNumbersSum2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | /**
4 | * Created by gaohan on 5/31/18.
5 | */
6 |
7 | public class ConsecutiveNumbersSum2 {
8 | public int consecutiveNumbersSum(int N) {
9 | // 2N = k(2x + k + 1)
10 | int ans = 0;
11 | for (int k = 1; k <= 2*N; ++k)
12 | if (2 * N % k == 0) {
13 | int y = 2 * N / k - k - 1;
14 | if (y % 2 == 0 && y >= 0)
15 | ans++;
16 | }
17 | return ans;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ContainsDuplicate.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 | /* Given an array of integers, find if the array contains any duplicates.
3 | * Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
4 | */
5 | /* TLE
6 | *
7 | */
8 | import java.util.HashSet;
9 |
10 | public class ContainsDuplicate {
11 |
12 | public boolean containsDuplicate(int[] nums) {
13 | HashSet set= new HashSet();
14 | for(int i=0;i map = new HashMap();
15 |
16 | for (int i = 0; i < nums.length; i++) {
17 | if (map.containsKey(nums[i]) && (i - map.get(nums[i])) <= k) {
18 | return true;
19 | }
20 |
21 | map.put(nums[i], i);
22 | }
23 |
24 | return false;
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ContainsDuplicateIII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | /* Given an array of integers, find out whether there are two distinct indices i and j in the array
4 | * such that the difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.
5 | */
6 | //TLE
7 | public class ContainsDuplicateIII {
8 | public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
9 | for (int l = 1; l <= k; l++) {
10 | for (int i = 0; i < nums.length - k; i++) {
11 | int j = i + l;
12 | if (Math.abs(nums[i] - nums[j])<=t)
13 | return true;
14 | }
15 | }
16 | return false;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ContiguousArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 | /**
3 | * Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
4 |
5 | Example 1:
6 | Input: [0,1]
7 | Output: 2
8 | Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
9 | Example 2:
10 | Input: [0,1,0]
11 | Output: 2
12 | Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
13 | Note: The length of the given binary array will not exceed 50,000.
14 | */
15 | public class ContiguousArray {
16 | public int findMaxLength(int[] nums) {
17 | return 0;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ConvertBinaryNumberinaLinkedListtoInteger.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | public class ConvertBinaryNumberinaLinkedListtoInteger {
6 |
7 | public int count = 0;
8 |
9 | public int getDecimalValue(ListNode head) {
10 | if (head.next == null) {
11 | count++;
12 | return head.val;
13 | } else {
14 | count++;
15 | return getDecimalValue(head.next) + head.val == 1 ? (int) Math.pow(2, count) : 0;
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ConvertBinaryNumberinaLinkedListtoInteger2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | public class ConvertBinaryNumberinaLinkedListtoInteger2 {
6 | public int getDecimalValue(ListNode head) {
7 | ListNode curr = head;
8 | int result = 0;
9 | while (curr != null) {
10 | result *= 2;
11 | if (curr.val == 1)
12 | result++;
13 | curr = curr.next;
14 | }
15 | return result;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ConvertIntegertotheSumofTwoNoZeroIntegers.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class ConvertIntegertotheSumofTwoNoZeroIntegers {
4 | public int[] getNoZeroIntegers(int n) {
5 | int num1 = 1, num2 = n - 1;
6 |
7 | while (hasZeroInDigit(num1) || hasZeroInDigit(num2)) {
8 | num1++;
9 | num2--;
10 | }
11 |
12 | return new int[]{num1, num2};
13 | }
14 |
15 | private boolean hasZeroInDigit(int n) {
16 | while (n > 0) {
17 | if (n % 10 == 0) {
18 | return true;
19 | }
20 | n /= 10;
21 | }
22 | return false;
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/ConvertIntegertotheSumofTwoNoZeroIntegers2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class ConvertIntegertotheSumofTwoNoZeroIntegers2 {
4 |
5 | public int[] getNoZeroIntegers(int n){
6 | int y=1;
7 | int x=n-1;
8 | while(String.valueOf(x).contains("0") || String.valueOf(y).contains("0")){
9 | y++;
10 | x--;
11 | }
12 | return new int[]{y,x};
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CountPrimes.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | import java.util.Arrays;
4 |
5 | /* Description:
6 | * Count the number of prime numbers less than a non-negative number, n
7 | */
8 | public class CountPrimes {
9 | public int countPrimes(int n) {
10 | boolean[] flag = new boolean[n];
11 | Arrays.fill(flag, true);
12 | for (int i = 2; i < Math.sqrt(n); i++) {
13 | if (flag[i]) {
14 | for (int j = 2 * i; j < n; j += i)
15 | flag[j] = false;
16 | }
17 | }
18 | int count = 0;
19 | for (int i = 2; i < n; i++)
20 | count = flag[i] == true ? count + 1 : count;
21 | return count;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CountPrimes2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | import java.util.BitSet;
4 | /* Description:
5 | * Count the number of prime numbers less than a non-negative number, n
6 | */
7 | public class CountPrimes2 {
8 | public int countPrimes(int n) {
9 | BitSet bs = new BitSet(n);
10 | bs.set(0);
11 | bs.set(1);
12 | int ind = 0, count = 0;
13 | while (ind < n) {
14 | ind = bs.nextClearBit(ind + 1);
15 | if (ind >= n)
16 | return count;
17 | count++;
18 | for (int i = 2 * ind; i < n; i += ind)
19 | bs.set(i);
20 | }
21 | return count;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CountSubstringswithOnlyOneDistinctLetter.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class CountSubstringswithOnlyOneDistinctLetter {
4 | public int countLetters(String S) {
5 | int ans = 0, repeat = 1;
6 | for (int i = 1; i < S.length(); ++i) {
7 | if (S.charAt(i) != S.charAt(i - 1)) { // previous char consectively occurs 'repeat' times.
8 | ans += repeat * (repeat + 1) / 2;
9 | repeat = 0;
10 | }
11 | repeat++;
12 | }
13 | return ans + repeat * (repeat + 1) / 2;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/c/CountSubstringswithOnlyOneDistinctLetter2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.c;
2 |
3 | public class CountSubstringswithOnlyOneDistinctLetter2 {
4 | public int countLetters(String S) {
5 | if (S.length() == 0)
6 | return 0;
7 |
8 | char prev = S.charAt(0);
9 | int rep = 1, count = 0;
10 | for (int i = 1; i <= S.length(); i++) {
11 | if (S.charAt(i) == prev) {
12 | rep++;
13 | continue;
14 | }
15 | count += rep * (rep + 1) / 2;
16 | rep = 1;
17 | prev = S.charAt(i);
18 | }
19 | count += rep * (rep + 1) / 2;
20 | return count;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DeleteNodeinaLinkedList.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /* Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
6 | * 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 -> 4 after
7 | */
8 | public class DeleteNodeinaLinkedList {
9 | public void deleteNode(ListNode node) {
10 | if(node==null)
11 | return;
12 | else{
13 | node.val=node.next.val;
14 | node.next=node.next.next;
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DesignHashSet.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 |
3 | import java.util.BitSet;
4 |
5 | public class DesignHashSet {
6 | class MyHashSet {
7 | BitSet b;
8 |
9 | /**
10 | * Initialize your data structure here.
11 | */
12 | public MyHashSet() {
13 | b = new BitSet(1000001);
14 | }
15 |
16 | public void add(int key) {
17 | b.set(key);
18 | }
19 |
20 | public void remove(int key) {
21 | b.clear(key);
22 | }
23 |
24 | /**
25 | * Returns true if this set contains the specified element
26 | */
27 | public boolean contains(int key) {
28 | return b.get(key);
29 | }
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DesignHashSet2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 |
3 | public class DesignHashSet2 {
4 | class MyHashSet {
5 | int[] arr;
6 |
7 | /**
8 | * Initialize your data structure here.
9 | */
10 | public MyHashSet() {
11 | arr = new int[1000000];
12 | }
13 |
14 | public void add(int key) {
15 | arr[key] = key + 1; // handle the case key=0
16 | }
17 |
18 | public void remove(int key) {
19 | arr[key] = 0;
20 | }
21 |
22 | /**
23 | * Returns true if this set did not already contain the specified element
24 | */
25 | public boolean contains(int key) {
26 | return (arr[key] != 0);
27 | }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DietPlanPerformance.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 |
3 | public class DietPlanPerformance {
4 | public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
5 | int total = 0;
6 | int points = 0;
7 | for (int i = 0; i < calories.length; i++) {
8 | total += calories[i];
9 | if (i >= k - 1) {
10 | if (i >= k)
11 | total -= calories[i - k];
12 | if (total > upper)
13 | points++;
14 | if (total < lower)
15 | points--;
16 | }
17 | }
18 | return points;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DivideChocolate.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 |
3 | public class DivideChocolate {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DivideTwoIntegers2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 | /* Divide two integers without using multiplication, division and mod operator.
3 | * If it is overflow, return MAX_INT.
4 | */
5 | public class DivideTwoIntegers2 {
6 | public int divide(int dividend, int divisor) {
7 | boolean signA = dividend >= 0, signB = divisor > 0;
8 | long num = Math.abs((long) dividend), div = Math.abs((long) divisor), res = 0, curr = 0;
9 | // using Long division
10 | for (int idx = 31; idx >= 0; idx--) {
11 | curr <<= 1;
12 | curr |= ((num >> idx) & 1);
13 | res = res << 1;
14 | if (curr >= div) {
15 | curr -= div;
16 | res |= 1;
17 | }
18 | }
19 | if (signA ^ signB)
20 | return -(int) res;
21 | return (int) res;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DominoandTrominoTiling.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 |
3 | public class DominoandTrominoTiling {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/d/DoubleLinkedListNode.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.d;
2 |
3 | /**
4 | * Created by gaohan on 5/27/18.
5 | */
6 | public class DoubleLinkedListNode {
7 | public int val;
8 | public int key;
9 | public DoubleLinkedListNode pre;
10 | public DoubleLinkedListNode next;
11 |
12 | public DoubleLinkedListNode(int key, int value) {
13 | val = value;
14 | this.key = key;
15 | this.next = null;
16 | this.pre = null;
17 | }
18 |
19 | public DoubleLinkedListNode(int val) {
20 | this.val = val;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/e/ElementAppearingMoreThan25PercentageInSortedArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.e;
2 |
3 | import java.util.HashMap;
4 |
5 | public class ElementAppearingMoreThan25PercentageInSortedArray {
6 | public int findSpecialInteger(int[] arr) {
7 | int n = arr.length, t = n / 4;
8 |
9 | for (int i = 0; i < n - t; i++) {
10 | if (arr[i] == arr[i + t]) {
11 | return arr[i];
12 | }
13 | }
14 | return -1;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/e/ExcelSheetColumnNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.e;
2 |
3 | /* Given a column title as appear in an Excel sheet, return its corresponding column number.
4 | * For example:
5 | * A -> 1
6 | * B -> 2
7 | * C -> 3
8 | * ...
9 | * Z -> 26
10 | * AA -> 27
11 | * AB -> 28
12 | */
13 | public class ExcelSheetColumnNumber {
14 | public int titleToNumber(String s) {
15 | int res = 0;
16 | for (int i = 0; i < s.length(); i++) {
17 | res = (s.charAt(i) - 'A' + 1) + res * 26;
18 | }
19 | return res;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/e/ExcelSheetColumnTitle.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.e;
2 |
3 | public class ExcelSheetColumnTitle {
4 | public String convertToTitle(int n) {
5 | StringBuilder result = new StringBuilder();
6 | while (n > 0) {
7 | n--;
8 | result.insert(0, (char) ('A' + n % 26));
9 | n /= 26;
10 | }
11 | return result.toString();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FactorialTrailingZeroes.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 | /* Given an integer n, return the number of trailing zeroes in n!.
3 | * Note: Your solution should be in logarithmic time complexity.
4 | */
5 | /* Because all trailing 0 is from factors 5 * 2.
6 | * But sometimes one number may have several 5 factors, for example, 25 have two 5 factors, 125 have three 5 factors.
7 | * In the n! operation, factors 2 is always ample. So we just count how many 5 factors in all number from 1 to n.
8 | */
9 | public class FactorialTrailingZeroes {
10 | public int trailingZeroes(int n) {
11 | int count=0;
12 | int div=5;
13 | while(n>0){
14 | count+=n/div;
15 | n/=div;
16 | }
17 | return count;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindKPairswithSmallestSums.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gaohannk/Leetcode/e0e111835b0fae2e27d80ac9e012f5052c6bd1a2/src/leetcode/algo/f/FindKPairswithSmallestSums.png
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindKPairswithSmallestSums2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gaohannk/Leetcode/e0e111835b0fae2e27d80ac9e012f5052c6bd1a2/src/leetcode/algo/f/FindKPairswithSmallestSums2.jpg
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindMinimuminRotatedSortedArray2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | /**
4 | * Suppose a sorted array is rotated at some pivot unknown to you beforehand.
5 | * (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
6 | * Find the minimum element.
7 | * You may assume no duplicate exists in the array.
8 | */
9 | // O(n)
10 | public class FindMinimuminRotatedSortedArray2 {
11 | public int findMin(int[] nums) {
12 | if (nums == null || nums.length == 0) {
13 | return 0;
14 | }
15 | for (int i = 0; i < nums.length - 1; i++) {
16 | if (nums[i + 1] < nums[i]) {
17 | return nums[i + 1];
18 | }
19 | }
20 | return nums[0];
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindNumberswithEvenNumberofDigits.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | public class FindNumberswithEvenNumberofDigits {
4 | public int findNumbers(int[] nums) {
5 | int res = 0;
6 | for (int num : nums) {
7 | int count = 0;
8 | while (num > 0) {
9 | num = num / 10;
10 | count++;
11 | }
12 | if (count % 2 == 0) {
13 | res++;
14 | }
15 | }
16 | return res;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindPeakElement2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | /* A peak element is an element that is greater than its neighbors.
4 | * Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
5 | * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
6 | * You may imagine that num[-1] = num[n] = -∞.
7 | * For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
8 | */
9 | public class FindPeakElement2 {
10 | public int findPeakElement(int[] num) {
11 | if (num.length <= 1)
12 | return 0;
13 | for (int i = 0; i < num.length - 1; i++) {
14 | if (num[i] > num[i + 1]) {
15 | return i;
16 | }
17 | }
18 | return num.length - 1;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindPivotIndex.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | public class FindPivotIndex {
4 | public int pivotIndex(int[] nums) {
5 | int sum = 0, leftsum = 0;
6 | for (int x : nums) {
7 | sum += x;
8 | }
9 | for (int i = 0; i < nums.length; ++i) {
10 | if (leftsum == sum - leftsum - nums[i]) {
11 | return i;
12 | }
13 | leftsum += nums[i];
14 | }
15 | return -1;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindtheCelebrity.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | public class FindtheCelebrity {
4 | public int findCelebrity(int n) {
5 | int p = 0;
6 | for (int i = 1; i < n && p < n; i++) {
7 | if (p != i && knows(p, i)) {
8 | p = i;
9 |
10 | }
11 | }
12 |
13 | for (int i = 0; i < n; i++) {
14 | if (i != p && knows(p, i) || !knows(i, p)) {
15 | return -1;
16 | }
17 | }
18 |
19 | return p;
20 | }
21 |
22 | private boolean knows(int p, int i) {
23 | return true;
24 | }
25 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindtheDifference3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | /*Given two strings s and t which consist of only lowercase letters.
4 |
5 | String t is generated by random shuffling string s and then add one more letter at a random position.
6 |
7 | Find the letter that was added in t.
8 |
9 | Example:
10 |
11 | Input:
12 | s = "abcd"
13 | t = "abcde"
14 |
15 | Output:
16 | e
17 |
18 | Explanation:
19 | 'e' is the letter that was added.
20 | */
21 | public class FindtheDifference3 {
22 |
23 | public char findTheDifference(String s, String t) {
24 | int sumOfS = s.chars().reduce((a, b) -> a + b).orElse(0);
25 | int sumOfT = t.chars().reduce((a, b) -> a + b).orElse(0);
26 | char diff = (char) (sumOfT - sumOfS);
27 | return diff;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FindtheDifference4.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | /*Given two strings s and t which consist of only lowercase letters.
4 |
5 | String t is generated by random shuffling string s and then add one more letter at a random position.
6 |
7 | Find the letter that was added in t.
8 |
9 | Example:
10 |
11 | Input:
12 | s = "abcd"
13 | t = "abcde"
14 |
15 | Output:
16 | e
17 |
18 | Explanation:
19 | 'e' is the letter that was added.
20 | */
21 | public class FindtheDifference4 {
22 | public char findTheDifference(String s, String t) {
23 | int sumOfS = 0, sumOfT=0;
24 | for (char a : s.toCharArray()) {
25 | sumOfS += a;
26 | }
27 | for (char a : t.toCharArray()) {
28 | sumOfT += a;
29 | }
30 | char diff = (char) (sumOfT - sumOfS);
31 | return diff;
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FirstMissingPositive.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | import java.util.Arrays;
4 |
5 | /* Given an unsorted integer array, find the first missing positive integer.
6 | * For example,
7 | * Given [1,2,0] return 3,
8 | * and [3,4,-1,1] return 2.
9 | * Your algorithm should run in O(n) time and uses constant space.
10 | */
11 | /* 排序之后查找。跳过非正整数部分和重复部分
12 | */
13 | public class FirstMissingPositive {
14 | public int firstMissingPositive(int[] A) {
15 | Arrays.sort(A);
16 | int count = 1;
17 | if (A.length == 0)
18 | return 1;
19 | for (int i = 0; i < A.length; i++) {
20 | if (A[i] <= 0)
21 | continue;
22 | if (i > 0 && A[i] == A[i - 1])
23 | continue;
24 | if (A[i] != count)
25 | break;
26 | else
27 | count++;
28 | }
29 | return count;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/Flatten2DVector.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | import java.util.Arrays;
4 | import java.util.Iterator;
5 |
6 | public class Flatten2DVector {
7 | class Vector2D {
8 |
9 | Iterator iter;
10 |
11 | public Vector2D(int[][] v) {
12 | iter = Arrays.asList(v)
13 | .stream()
14 | .flatMapToInt(i -> Arrays.stream(i))
15 | .iterator();
16 | }
17 |
18 | public int next() {
19 | return iter.next();
20 | }
21 |
22 | public boolean hasNext() {
23 | return iter.hasNext();
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/FlipGameII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 | /* You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner.
3 | * Write a function to determine if the starting player can guarantee a win.
4 | * For example, given s = "++++", return true. The starting player can guarantee a win by flipping the middle "++" to become "+--+".
5 | * Follow up:
6 | * Derive your algorithm's runtime complexity.
7 | */
8 | public class FlipGameII {
9 |
10 | }
11 |
--------------------------------------------------------------------------------
/src/leetcode/algo/f/GraphValidTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.f;
2 |
3 | public class GraphValidTree {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/g/GraphValidTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.g;
2 |
3 | public class GraphValidTree {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/g/GreatestSumDivisiblebyThree2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.g;
2 |
3 | /**
4 | * Represent the state as DP[pos][mod]: maximum possible sum starting in the position "pos" in the array where the current sum modulo 3 is equal to mod.
5 | */
6 | public class GreatestSumDivisiblebyThree2 {
7 | public int maxSumDivThree(int[] A) {
8 | int[] dp = new int[]{0, Integer.MIN_VALUE, Integer.MIN_VALUE};
9 | for (int a : A) {
10 | int[] dp2 = new int[3];
11 | for (int i = 0; i < 3; ++i)
12 | dp2[(i + a) % 3] = Math.max(dp[(i + a) % 3], dp[i] + a);
13 | dp = dp2;
14 | }
15 | return dp[0];
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/g/GroupsofSpecialEquivalentStrings.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.g;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | /**
8 | * LeetCode 893
9 | */
10 | public class GroupsofSpecialEquivalentStrings {
11 | public int numSpecialEquivGroups(String[] A) {
12 | Set seen = new HashSet();
13 | for (String S : A) {
14 | int[] count = new int[52];
15 | for (int i = 0; i < S.length(); i++)
16 | count[S.charAt(i) - 'a' + 26 * (i % 2)]++;
17 | seen.add(Arrays.toString(count));
18 | }
19 | return seen.size();
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/g/GroupthePeopleGiventheGroupSizeTheyBelongTo2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.g;
2 |
3 | import java.util.*;
4 |
5 | public class GroupthePeopleGiventheGroupSizeTheyBelongTo2 {
6 | public List> groupThePeople(int[] groupSizes) {
7 | List> res = new ArrayList();
8 | Map> groups = new HashMap<>();
9 | for (int i = 0; i < groupSizes.length; i++) {
10 | List list = groups.putIfAbsent(groupSizes[i], new ArrayList());
11 | list.add(i);
12 | if (list.size() == groupSizes[i]) {
13 | res.add(new ArrayList<>(list));
14 | list.clear();
15 | }
16 | }
17 | return res;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/g/GuessGame.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.g;
2 |
3 | public abstract class GuessGame {
4 | int target;
5 |
6 | public abstract int guess(int num);
7 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/h/HIndexII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.h;
2 | /* Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
3 | * Hint:
4 | * Expected runtime complexity is in O(log n) and the input is sorted.
5 | */
6 |
7 | public class HIndexII {
8 | public static int hIndex(int[] citations) {
9 | if (citations.length == 0)
10 | return 0;
11 | if (citations.length == 1)
12 | return citations[0] >= 1 ? 1 : 0;
13 | int h = 1;
14 | for (int i = citations.length - 1; i >= 0; i--) {
15 | if (h > citations[i])
16 | return h - 1;
17 | h++;
18 | }
19 | return h-1;
20 | }
21 |
22 | public static void main(String[] args) {
23 | int[] a = { 1,12,15 };
24 | System.out.println(hIndex(a));
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/h/HammingDistance.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.h;
2 |
3 | /**
4 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
5 |
6 | Given two integers x and y, calculate the Hamming distance.
7 |
8 | Note:
9 | 0 ≤ x, y < 231.
10 |
11 | Example:
12 |
13 | Input: x = 1, y = 4
14 |
15 | Output: 2
16 |
17 | Explanation:
18 | 1 (0 0 0 1)
19 | 4 (0 1 0 0)
20 | ↑ ↑
21 |
22 | The above arrows point to positions where the corresponding bits are different.
23 | */
24 | public class HammingDistance {
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/IncreasingOrderSearchTree2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 |
4 | import leetcode.common.TreeNode;
5 |
6 | public class IncreasingOrderSearchTree2 {
7 | TreeNode cur;
8 | public TreeNode increasingBST(TreeNode root) {
9 | TreeNode ans = new TreeNode(0);
10 | cur = ans;
11 | inorder(root);
12 | return ans.right;
13 | }
14 |
15 | public void inorder(TreeNode node) {
16 | if (node == null) return;
17 | inorder(node.left);
18 | node.left = null;
19 | cur.right = cur = node;
20 | inorder(node.right);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/InorderSuccessorinBST2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | /* Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
6 | * Note: If the given node has no in-order successor in the tree, return null.
7 | */
8 | /* Time Complexity - O(h), Space Complexity - O(1)
9 | */
10 | public class InorderSuccessorinBST2 {
11 |
12 | public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
13 | if (root == null || p == null) {
14 | return null;
15 | }
16 | TreeNode successor = null;
17 | while (root != null) {
18 | if (root.val < p.val) {
19 | root = root.right;
20 | } else {
21 | successor = root;
22 | root = root.left;
23 | }
24 | }
25 | return successor;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/InsertintoaBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | public class InsertintoaBinarySearchTree {
6 | public TreeNode insertIntoBST(TreeNode root, int val) {
7 | if (root == null) {
8 | return new TreeNode(val);
9 | }
10 | if (root.val > val) {
11 | root.left = insertIntoBST(root.left, val);
12 | } else {
13 | root.right = insertIntoBST(root.right, val);
14 | }
15 | return root;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/InsertionSortList.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /* Sort a linked list using insertion sort.
6 | */
7 | public class InsertionSortList {
8 | public ListNode insertionSortList(ListNode head) {
9 | if (head == null)
10 | return null;
11 | ListNode helper = new ListNode(0);
12 | ListNode pre = helper;
13 | ListNode cur = head;
14 | while (cur != null) {
15 | pre = helper;
16 | while (pre.next != null && pre.next.val <= cur.val) {
17 | pre = pre.next;
18 | }
19 |
20 | ListNode next = cur.next;
21 | cur.next = pre.next;
22 | pre.next = cur;
23 | cur = next;
24 | }
25 | return helper.next;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/InsertionSortList2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 | /* Sort a linked list using insertion sort.
3 | */
4 | public class InsertionSortList2 {
5 |
6 | }
7 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/IntegertoRoman.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 | /* Given an integer, convert it to a Roman numeral.
4 | * Input is guaranteed to be within the range from 1 to 3999.
5 | */
6 | public class IntegertoRoman {
7 | // iteration
8 | public String intToRoman(int num) {
9 | int[] int_dict = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
10 | String[] roman_dict = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
11 | String roman = "";
12 | int i = 0;
13 | while (num > 0) {
14 | if (num - int_dict[i] >= 0) {
15 | roman += roman_dict[i];
16 | num -= int_dict[i];
17 | } else
18 | i++;
19 | }
20 | return roman;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/IntegertoRoman2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 | /* Given an integer, convert it to a Roman numeral.
3 | * Input is guaranteed to be within the range from 1 to 3999.
4 | */
5 | public class IntegertoRoman2 {
6 | // recursive
7 | public String intToRoman(int num) {
8 | int[] int_dict = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
9 | String[] roman_dict = { "M", "CM", "D", "CD", "C", "XC", "L", "XL",
10 | "X", "IX", "V", "IV", "I" };
11 | for (int i = 0; i <= int_dict.length - 1; i++) {
12 | if (num - int_dict[i] >= 0)
13 | return roman_dict[i] + intToRoman(num - int_dict[i]);
14 | }
15 | return "";
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/IntersectionofThreeSortedArrays2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class IntersectionofThreeSortedArrays2 {
7 | public List arraysIntersection(int[] arr1, int[] arr2, int[] arr3) {
8 | //array to hold count of each element, value of element is an index
9 | int[] c = new int[2001];
10 | for (int n : arr1) c[n]++;
11 | for (int n : arr2) c[n]++;
12 | for (int n : arr3) c[n]++;
13 |
14 | //fill result list, if count = 3 - this element is in every array
15 | List res = new ArrayList();
16 | for (int i = 1; i <= 2000; i++) {
17 | if (c[i] == 3)
18 | res.add(i);
19 | }
20 | return res;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/Interval.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 | public class Interval {
4 | public int start;
5 | public int end;
6 | Interval() {
7 | start = 0;
8 | end = 0;
9 | }
10 | public Interval(int s, int e) {
11 | start = s;
12 | end = e;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/leetcode/algo/i/InvertBinaryTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.i;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | /* invert a binary tree.
6 | * 4
7 | * / \
8 | * 2 7
9 | * / \ / \
10 | *1 3 6 9
11 | *to
12 | * 4
13 | * / \
14 | * 7 2
15 | * / \ / \
16 | *9 6 3 1
17 | */
18 | public class InvertBinaryTree {
19 | public TreeNode invertTree(TreeNode root) {
20 | if (root == null)
21 | return null;
22 | TreeNode node = root.left;
23 | root.left = root.right;
24 | root.right = node;
25 | invertTree(root.left);
26 | invertTree(root.right);
27 | return root;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/leetcode/algo/j/JumpGame.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.j;
2 | /* Given an array of non-negative integers, you are initially positioned at the first index of the array.
3 | * Each element in the array represents your maximum jump length at that position.
4 | * Determine if you are able to reach the last index.
5 | * For example:
6 | * A = [2,3,1,1,4], return true.
7 | * A = [3,2,1,0,4], return false.
8 | */
9 | /* 优化解法,只需要顺序扫描数组,记录下能够到达的最远位置
10 | */
11 | public class JumpGame {
12 | public boolean canJump(int[] A) {
13 | int farest = 0;
14 | for (int i = 0; i <= farest; i++) {
15 | if (A[i] + i > farest)
16 | farest = A[i] + i;
17 | if (farest >= A.length - 1)
18 | return true;
19 | }
20 | return false;
21 | }
22 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/j/JumpGame2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.j;
2 | /* Given an array of non-negative integers, you are initially positioned at the first index of the array.
3 | * Each element in the array represents your maximum jump length at that position.
4 | * Determine if you are able to reach the last index.
5 | * For example:
6 | * A = [2,3,1,1,4], return true.
7 | * A = [3,2,1,0,4], return false.
8 | */
9 | public class JumpGame2 {
10 | public boolean canJump(int[] nums) {
11 | int reachable = 0;
12 | for (int i=0; i reachable) return false;
14 | reachable = Math.max(reachable, i + nums[i]);
15 | }
16 | return true;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/j/JumpGameII3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.j;
2 |
3 | /*The main idea is based on greedy. Let's say the range of the current jump is [curBegin, curEnd], curFarthest is the farthest point that all points in [curBegin, curEnd]
4 | can reach. Once the current point reaches curEnd, then trigger another jump, and set the new curEnd with curFarthest, then keep the above steps, as the following:
5 | */
6 | public class JumpGameII3 {
7 | public int jump(int[] A) {
8 | int jumps = 0, curEnd = 0, curFarthest = 0;
9 | for (int i = 0; i < A.length - 1; i++) {
10 | curFarthest = Math.max(curFarthest, i + A[i]);
11 | if (i == curEnd) {
12 | jumps++;
13 | curEnd = curFarthest;
14 | }
15 | }
16 | return jumps;
17 | }
18 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/k/KthLargestElementinanArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.k;
2 |
3 | /* Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
4 | * For example,
5 | * Given [3,2,1,5,6,4] and k = 2, return 5.
6 | * Note: You may assume k is always valid, 1 ≤ k ≤ array's length.
7 | */
8 | import java.util.Arrays;
9 |
10 | public class KthLargestElementinanArray {
11 | public int findKthLargest(int[] nums, int k) {
12 | Arrays.sort(nums);
13 | return nums[nums.length - k];
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LargestMultipleofThree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | public class LargestMultipleofThree {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LargestTriangleArea.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | public class LargestTriangleArea {
4 | public double largestTriangleArea(int[][] points) {
5 | int N = points.length;
6 | double ans = 0;
7 | for (int i = 0; i < N; i++) {
8 | for (int j = i + 1; j < N; j++) {
9 | for (int k = j + 1; k < N; k++) {
10 | ans = Math.max(ans, area(points[i], points[j], points[k]));
11 | }
12 | }
13 | }
14 | return ans;
15 | }
16 |
17 | public double area(int[] P, int[] Q, int[] R) {
18 | return 0.5 * Math.abs(P[0] * Q[1] + Q[0] * R[1] + R[0] * P[1]
19 | - P[1] * Q[0] - Q[1] * R[0] - R[1] * P[0]);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LargestUniqueNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class LargestUniqueNumber {
7 | public int largestUniqueNumber(int[] A) {
8 | Map map = new HashMap<>();
9 | for (int i = 0; i < A.length; i++) {
10 | map.put(A[i], map.getOrDefault(A[i], 0) + 1);
11 | }
12 | int max = Integer.MIN_VALUE;
13 | for (int value : map.keySet()) {
14 | if (map.get(value) == 1) {
15 | max = Math.max(value, max);
16 | }
17 | }
18 | return max == Integer.MIN_VALUE ? -1 : max;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LargestUniqueNumber2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class LargestUniqueNumber2 {
7 | public int largestUniqueNumber(int[] A) {
8 | int[] cnt = new int[1001];
9 | for (int value : A) {
10 | cnt[value]++;
11 | }
12 | for (int x = 1000; x > 0; x--) {
13 | if (cnt[x] == 1) {
14 | return x;
15 | }
16 | }
17 | return -1;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LengthofLastWord.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 | /* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
3 | * If the last word does not exist, return 0.
4 | * Note: A word is defined as a character sequence consists of non-space characters only.
5 | * For example,
6 | * Given s = "Hello World",
7 | * return 5.
8 | */
9 | public class LengthofLastWord {
10 | public int lengthOfLastWord(String s) {
11 | String ss = s.trim();
12 | return ss.length() - 1 - ss.lastIndexOf(' ');
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LengthofLastWord2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 | /* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
3 | * If the last word does not exist, return 0.
4 | * Note: A word is defined as a character sequence consists of non-space characters only.
5 | * For example,
6 | * Given s = "Hello World",
7 | * return 5.
8 | */
9 | public class LengthofLastWord2 {
10 | public int lengthOfLastWord(String s) {
11 | if (s != null && !s.trim().equals("")) {
12 | String[] arr = s.trim().split(" ");
13 | int length = arr[arr.length - 1].length();
14 | return length;
15 | }
16 | return 0;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LengthofLastWord3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 | /* Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
3 | * If the last word does not exist, return 0.
4 | * Note: A word is defined as a character sequence consists of non-space characters only.
5 | * For example,
6 | * Given s = "Hello World",
7 | * return 5.
8 | */
9 | public class LengthofLastWord3 {
10 | public int lengthOfLastWord(String s) {
11 | if (s == null || s.length() == 0)
12 | return 0;
13 | int count = 0;
14 | for (int i = s.length() - 1; i >=0; i--) {
15 | if (s.charAt(i) != ' ')
16 | count++;
17 | if (s.charAt(i) == ' ' && count != 0) {
18 | return count;
19 | }
20 | }
21 | return count;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LinkedListComponents.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | import java.util.HashSet;
6 | import java.util.Set;
7 |
8 | /**
9 | * 817. Linked List Components
10 | */
11 | public class LinkedListComponents {
12 | public int numComponents(ListNode head, int[] G) {
13 | Set Gset = new HashSet();
14 | for (int x : G) {
15 | Gset.add(x);
16 | }
17 |
18 | ListNode cur = head;
19 | int ans = 0;
20 |
21 | while (cur != null) {
22 | if (Gset.contains(cur.val) &&
23 | (cur.next == null || !Gset.contains(cur.next.val)))
24 | ans++;
25 | cur = cur.next;
26 | }
27 |
28 | return ans;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LinkedListCycle.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | /* Given a linked list, determine if it has a cycle in it.
4 | * Follow up:
5 | * Can you solve it without using extra space?
6 | */
7 |
8 | import leetcode.common.ListNode;
9 |
10 | public class LinkedListCycle {
11 |
12 | public boolean hasCycle(ListNode head) {
13 | if (head == null || head.next == null) {
14 | return false;
15 | }
16 | ListNode fast = head.next, slow = head;
17 | while (fast != null && fast.next != null) {
18 | fast = fast.next.next;
19 | slow = slow.next;
20 | if (fast == slow) {
21 | return true;
22 | }
23 | }
24 |
25 | return false;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LinkedListCycle2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | /* Given a linked list, determine if it has a cycle in it.
4 | * Follow up:
5 | * Can you solve it without using extra space?
6 | */
7 |
8 | import leetcode.common.ListNode;
9 |
10 | import java.util.HashSet;
11 | import java.util.Set;
12 |
13 | public class LinkedListCycle2 {
14 | public boolean hasCycle(ListNode head) {
15 | Set nodesSeen = new HashSet<>();
16 | while (head != null) {
17 | if (nodesSeen.contains(head)) {
18 | return true;
19 | } else {
20 | nodesSeen.add(head);
21 | }
22 | head = head.next;
23 | }
24 | return false;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LongestContinuousIncreasingSubsequence.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | public class LongestContinuousIncreasingSubsequence {
4 | public int findLengthOfLCIS(int[] nums) {
5 | int ans = 0, anchor = 0;
6 | for (int i = 1; i < nums.length; i++) {
7 | if (i > 0 && nums[i - 1] >= nums[i]) {
8 | anchor = i;
9 | }
10 | ans = Math.max(ans, i - anchor + 1);
11 | }
12 | return ans;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LongestContinuousIncreasingSubsequence2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | public class LongestContinuousIncreasingSubsequence2 {
4 | public int findLengthOfLCIS(int[] nums) {
5 | if (nums.length == 0) {
6 | return 0;
7 | }
8 | int length = 1, temp = 1;
9 | for (int i = 0; i < nums.length - 1; i++) {
10 | if (nums[i] < nums[i + 1]) {
11 | temp++;
12 | } else {
13 | length = Math.max(length, temp);
14 | temp = 1;
15 | }
16 | }
17 | length = Math.max(length, temp);
18 | return length;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LongestTurbulentSubarray2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | public class LongestTurbulentSubarray2 {
4 | public int maxTurbulenceSize(int[] A) {
5 | int res = 1;
6 | int start = 0;
7 |
8 | for (int i = 1; i < A.length; i++) {
9 | int flag = Integer.compare(A[i-1], A[i]);
10 | if (flag == 0) {
11 | start = i;
12 | } else if (i == A.length - 1 || flag * Integer.compare(A[i], A[i+1]) != -1) {
13 | res = Math.max(res, i - start + 1);
14 | start = i;
15 | }
16 | }
17 |
18 | return res;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LongestWordinDictionary3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | import java.util.Arrays;
4 | import java.util.HashSet;
5 | import java.util.Set;
6 |
7 | public class LongestWordinDictionary3 {
8 | public String longestWord(String[] words) {
9 | Arrays.sort(words);
10 | Set built = new HashSet();
11 | String res = "";
12 | for (String w : words) {
13 | if (w.length() == 1 || built.contains(w.substring(0, w.length() - 1))) {
14 | res = w.length() > res.length() ? w : res;
15 | built.add(w);
16 | }
17 | }
18 | return res;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/l/LongestWordinDictionarythroughDeleting.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.l;
2 |
3 | public class LongestWordinDictionarythroughDeleting {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MajorityElement2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | public class MajorityElement2 {
4 | public int majorityElement(int[] num) {
5 | int maj=0;
6 | int count = 0;
7 | for (int i = 0; i < num.length; i++){
8 | if (count == 0){
9 | maj = num[i];
10 | count++;
11 | }
12 | else if (num[i] == maj){
13 | count++;
14 | if (count > num.length/2) return maj;
15 | }
16 | else count--;
17 | }
18 | return maj;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MatrixBlockSum.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | public class MatrixBlockSum {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaxConsecutiveOnesII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | /**
4 | * Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.
5 |
6 | Example 1:
7 |
8 | Input: [1,0,1,1,0]
9 | Output: 4
10 | Explanation: Flip the first zero will get the the maximum number of consecutive 1s.
11 | After flipping, the maximum number of consecutive 1s is 4.
12 | Note:
13 |
14 | The input array will only contain 0 and 1.
15 | The length of input array is a positive integer and will not exceed 10,000
16 |
17 | */
18 | public class MaxConsecutiveOnesII {
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximalSquare2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | public class MaximalSquare2 {
4 |
5 | }
6 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumDepthofBinaryTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | /* Given a binary tree, find its maximum depth.
6 | * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
7 | */
8 | public class MaximumDepthofBinaryTree {
9 | public int maxDepth(TreeNode root) {
10 | return helper(root, 0);
11 | }
12 |
13 | public int helper(TreeNode node, int depth) {
14 | if (node == null)
15 | return depth;
16 | int left=helper(node.left,depth+1);
17 | int right=helper(node.right,depth+1);
18 | return Math.max(left,right);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumDepthofBinaryTree2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | /* Given a binary tree, find its maximum depth.
6 | * The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
7 | */
8 | public class MaximumDepthofBinaryTree2 {
9 | public int maxDepth(TreeNode root) {
10 | if (root == null)
11 | return 0;
12 | int left = maxDepth(root.left);
13 | int right = maxDepth(root.right);
14 | return Math.max(left,right)+1;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumDistanceinArrays.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import java.util.List;
4 |
5 | public class MaximumDistanceinArrays {
6 | public int maxDistance(List> arrays) {
7 | int min = arrays.get(0).get(0);
8 | int max = arrays.get(0).get(arrays.get(0).size() - 1);
9 | int diff = Integer.MIN_VALUE;
10 | for (int i = 1; i < arrays.size(); i++) {
11 | int large = arrays.get(i).get(arrays.get(i).size() - 1);
12 | int small = arrays.get(i).get(0);
13 | diff = Math.max(Math.max(diff, large - min), max - small);
14 | min = Math.min(min, small);
15 | max = Math.max(max, large);
16 | }
17 | return diff;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumGap.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 | /* Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
3 | * Try to solve it in linear time/space.
4 | * Return 0 if the array contains less than 2 elements.
5 | * You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
6 | */
7 | import java.util.Arrays;
8 |
9 | public class MaximumGap {
10 | public int maximumGap(int[] num) {
11 | Arrays.sort(num);
12 | int max = 0;
13 | for (int i = 1; i < num.length; i++) {
14 | if (Math.abs(num[i] - num[i - 1]) > max)
15 | max = Math.abs(num[i] - num[i - 1]);
16 | }
17 | return max;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumProductSubarray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | /* Find the contiguous subarray within an array (containing at least one number) which has the largest product.
4 | * For example, given the array [2,3,-2,4],
5 | * the contiguous subarray [2,3] has the largest product = 6.
6 | */
7 | public class MaximumProductSubarray {
8 | public int maxProduct(int[] A) {
9 | if (A == null || A.length == 0)
10 | return 0;
11 |
12 | int curMax = A[0];
13 | int curMin = A[0];
14 | int max = A[0];
15 |
16 | for (int i = 1; i < A.length; i++) {
17 | int temp = curMax * A[i];
18 | curMax = Math.max(A[i], Math.max(curMax * A[i], curMin * A[i]));
19 | curMin = Math.min(A[i], Math.min(temp, curMin * A[i]));
20 | max = Math.max(curMax, max);
21 | }
22 | return max;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumSizeSubarraySumEqualsk.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class MaximumSizeSubarraySumEqualsk {
7 | public int maxSubArrayLen(int[] nums, int k) {
8 | Map map = new HashMap();
9 | map.put(0, -1);
10 | int sum = 0, max = 0;
11 | for (int i = 0; i < nums.length; i++) {
12 | sum += nums[i];
13 | if (map.containsKey(sum - k)) {
14 | max = Math.max(max, i - map.get(sum - k));
15 | }
16 | map.putIfAbsent(sum, i);
17 | }
18 | return max;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumSubarray2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | /* Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
4 | * For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
5 | * the contiguous subarray [4,−1,2,1] has the largest sum = 6.
6 | * More practice:
7 | * If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach,
8 | * which is more subtle.
9 | */
10 |
11 | public class MaximumSubarray2 {
12 | public int maxSubArray(int[] A) {
13 | int max = A[0];
14 | int maxEndHere = A[0];
15 | for (int i = 1; i < A.length; i++) {
16 | maxEndHere = Math.max(A[i], maxEndHere + A[i]);
17 | max = Math.max(max, maxEndHere);
18 | }
19 | return max;
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MaximumSumofTwoNonOverlappingSubarrays.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | public class MaximumSumofTwoNonOverlappingSubarrays {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MeetingRooms.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import java.util.Arrays;
4 |
5 | /**
6 | * Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend all meetings.
7 | *
8 | * For example,
9 | * Given [[0, 30],[5, 10],[15, 20]],
10 | * return false.
11 | */
12 | public class MeetingRooms {
13 | public static boolean canAttendMeetings(int[][] intervals) {
14 | Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]);
15 | int endTime = 0;
16 | for (int i = 0; i < intervals.length; i++) {
17 | if (intervals[i][0] < endTime)
18 | return false;
19 | else
20 | endTime = intervals[i][1];
21 | }
22 | return true;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MergeSortedArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | /* Given two sorted integer arrays A and B, merge B into A as one sorted array.
4 | * Note:
5 | * You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B.
6 | * The number of elements initialized in A and B are m and n respectively.
7 | */
8 | public class MergeSortedArray {
9 | public void merge(int A[], int m, int B[], int n) {
10 | int i = m + n - 1;
11 | int p1 = m - 1;
12 | int p2 = n - 1;
13 | while (p1 >= 0 && p2 >= 0) {
14 | A[i--] = A[p1] > B[p2] ? A[p1--] : B[p2--];
15 | }
16 | while (p2 >= 0) {
17 | A[i--] = B[p2--];
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MergeTwoSortedLists2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /* Merge two sorted linked lists and return it as a new list.
6 | * The new list should be made by splicing together the nodes of the first two lists.
7 | */
8 | /* recursion solution
9 | */
10 | public class MergeTwoSortedLists2 {
11 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
12 | if (l1 == null && l2 == null)
13 | return null;
14 | if (l1 == null)
15 | return l2;
16 | if (l2 == null)
17 | return l1;
18 |
19 | ListNode p = new ListNode(0);
20 | if (l1.val < l2.val) {
21 | p.next = l1;
22 | l1.next = mergeTwoLists(l1.next, l2);
23 | } else {
24 | p.next = l2;
25 | l2.next = mergeTwoLists(l1, l2.next);
26 | }
27 | return p.next;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MinimumAbsoluteDifferenceinBST.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | public class MinimumAbsoluteDifferenceinBST {
6 | int min = Integer.MAX_VALUE;
7 | Integer prev = null;
8 |
9 | public int getMinimumDifference(TreeNode root) {
10 | if (root == null)
11 | return -1;
12 | getMinimumDifference(root.left);
13 | if (prev != null)
14 | min = Math.min(min, root.val - prev);
15 | prev = root.val;
16 | getMinimumDifference(root.right);
17 |
18 | return min;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MinimumDepthofBinaryTree2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | /** Given a binary tree, find its minimum depth.
6 | * The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
7 | */
8 |
9 | public class MinimumDepthofBinaryTree2 {
10 | public int minDepth(TreeNode root) {
11 | if (root == null)
12 | return 0;
13 | if (root.left == null && root.right == null)
14 | return 1;
15 | if (root.left == null)
16 | return 1 + minDepth(root.right);
17 | else if (root.right == null)
18 | return 1 + minDepth(root.left);
19 | else
20 | return 1 + Math.min(minDepth(root.left), minDepth(root.right));
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MinimumDistanceBetweenBSTNodes.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | import java.util.ArrayList;
6 | import java.util.List;
7 |
8 | public class MinimumDistanceBetweenBSTNodes {
9 | public int minDiffInBST(TreeNode root) {
10 | List res = new ArrayList();
11 | inorder(res, root);
12 | int min = Integer.MAX_VALUE;
13 | for (int i = 1; i < res.size(); i++) {
14 | min = Math.min(min, res.get(i) - res.get(i - 1));
15 | }
16 | return min;
17 | }
18 |
19 | private void inorder(List res, TreeNode root) {
20 | if (root == null)
21 | return;
22 | inorder(res, root.left);
23 | res.add(root.val);
24 | inorder(res, root.right);
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MinimumIndexSumofTwoLists2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashMap;
5 | import java.util.List;
6 |
7 | public class MinimumIndexSumofTwoLists2 {
8 | public String[] findRestaurant(String[] list1, String[] list2) {
9 | List res = new ArrayList<>();
10 | for (int sum = 0; sum < list1.length + list2.length - 1; sum++) {
11 | for (int i = 0; i <= sum; i++) {
12 | if (i < list1.length && sum - i < list2.length && list1[i].equals(list2[sum - i]))
13 | res.add(list1[i]);
14 | }
15 | if (res.size() > 0)
16 | break;
17 | }
18 | return res.toArray(new String[res.size()]);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MinimumKnightMoves.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | /**
4 | * In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].
5 | *
6 | * A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.
7 | *
8 | *
9 | *
10 | * Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.
11 | *
12 | *
13 | *
14 | * Example 1:
15 | *
16 | * Input: x = 2, y = 1
17 | * Output: 1
18 | * Explanation: [0, 0] → [2, 1]
19 | * Example 2:
20 | *
21 | * Input: x = 5, y = 5
22 | * Output: 4
23 | * Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]
24 | */
25 | public class MinimumKnightMoves {
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MinimumSizeSubarraySum3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | import java.util.Deque;
4 | import java.util.LinkedList;
5 |
6 | public class MinimumSizeSubarraySum3 {
7 | public static int minSubArrayLen(int s, int[] nums) {
8 | Deque queue = new LinkedList<>();
9 | int minLength = Integer.MAX_VALUE;
10 | int sum = 0;
11 | for (int num : nums) {
12 | sum += num;
13 | queue.offer(num);
14 | if (sum >= s) {
15 | while (sum - queue.peek() >= s)
16 | sum -= queue.poll();
17 | minLength = Math.min(minLength, queue.size());
18 | }
19 | }
20 | return sum < s ? 0 : minLength;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/MissingNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 | /*
3 | * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
4 | * For example,
5 | * Given nums = [0, 1, 3] return 2.
6 | */
7 | import java.util.Arrays;
8 |
9 | public class MissingNumber {
10 | public int missingNumber(int[] nums) {
11 | if(nums==null||nums.length==0)
12 | return 0;
13 | Arrays.sort(nums);
14 | for(int i=0;i calendar;
8 |
9 | MyCalendar() {
10 | calendar = new TreeMap();
11 | }
12 |
13 | public boolean book(int start, int end) {
14 | Integer prev = calendar.floorKey(start),
15 | next = calendar.ceilingKey(start);
16 | if ((prev == null || calendar.get(prev) <= start) &&
17 | (next == null || end <= next)) {
18 | calendar.put(start, end);
19 | return true;
20 | }
21 | return false;
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/m/NumberofValidSubarrays.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.m;
2 |
3 | public class NumberofValidSubarrays {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NewTwentyOneGame.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NewTwentyOneGame {
4 | public double new21Game(int N, int K, int W) {
5 | return 0.0;
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NextGreaterElementIII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NextGreaterElementIII {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberComplement.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NumberComplement {
4 | public int findComplement(int x) {
5 | int mask = 1;
6 | while (mask > 0 && mask <= x) {
7 | x = x ^ mask;
8 | mask = mask << 1;
9 | }
10 | return x;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/Numberof1Bits.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class Numberof1Bits {
4 | // you need to treat n as an unsigned value
5 | public int hammingWeight(int n) {
6 | int num = 32;
7 | int count = 0;
8 | while (num-- > 0) {
9 | if (((1 << num) & n) !=0)
10 | count++;
11 | }
12 | return count;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberofBurgerswithNoWasteofIngredients.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class NumberofBurgerswithNoWasteofIngredients {
7 | public List numOfBurgers(int t, int c) {
8 | List res = new ArrayList<>();
9 | if (t % 2 != 0 || t / 2 - c < 0 || 4 * c - t < 0)
10 | return res;
11 | res.add(t / 2 - c);
12 | res.add(2 * c - t / 2);
13 | return res;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberofDaysBetweenTwoDates2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | import java.time.LocalDate;
4 | import java.time.temporal.ChronoUnit;
5 |
6 | public class NumberofDaysBetweenTwoDates2 {
7 |
8 | public int daysBetweenDates(String date1, String date2) {
9 | //24-May-2017, change this to your desired Start Date
10 | LocalDate dateBefore = LocalDate.parse(date1);
11 | //29-July-2017, change this to your desired End Date
12 | LocalDate dateAfter = LocalDate.parse(date2);
13 | return (int) Math.abs(ChronoUnit.DAYS.between(dateBefore, dateAfter));
14 |
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberofDaysinaMonth.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NumberofDaysinaMonth {
4 | public int numberOfDays(int Y, int M) {
5 | boolean isLeapYear = false;
6 | if ((Y % 4 == 0 && Y % 100 != 0) || Y % 400 == 0) {
7 | isLeapYear = true;
8 | }
9 | if (M <= 7) {
10 | if (M == 2)
11 | return isLeapYear ? 29 : 28;
12 | return (M % 2 == 0) ? 30 : 31;
13 | }
14 | return (M % 2 == 0) ? 31 : 30;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberofSegmentsinaString.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NumberofSegmentsinaString {
4 | public int countSegments(String s) {
5 | String trimmed = s.trim();
6 | if (trimmed.equals("")) {
7 | return 0;
8 | }
9 | return trimmed.split("\\s+").length;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberofSegmentsinaString2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NumberofSegmentsinaString2 {
4 | public int countSegments(String s) {
5 | int segmentCount = 0;
6 |
7 | for (int i = 0; i < s.length(); i++) {
8 | if ((i == 0 || s.charAt(i-1) == ' ') && s.charAt(i) != ' ') {
9 | segmentCount++;
10 | }
11 | }
12 |
13 | return segmentCount;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberofSubarraysofSizeKandAverageGreaterthanorEqualtoThreshold.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NumberofSubarraysofSizeKandAverageGreaterthanorEqualtoThreshold {
4 | public int numOfSubarrays(int[] arr, int k, int threshold) {
5 | int total = k * threshold;
6 | int sum = 0;
7 | int res = 0;
8 | for (int i = 0; i < k; i++) {
9 | sum += arr[i];
10 | }
11 | if (sum >= total) {
12 | res++;
13 | }
14 | for (int i = k; i < arr.length; i++) {
15 | sum -= arr[i - k];
16 | sum += arr[i];
17 | System.out.println(sum);
18 | if (sum >= total) {
19 | res++;
20 | }
21 | }
22 | return res;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/n/NumberofSubarraysofSizeKandAverageGreaterthanorEqualtoThreshold2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.n;
2 |
3 | public class NumberofSubarraysofSizeKandAverageGreaterthanorEqualtoThreshold2 {
4 | public int numOfSubarrays(int[] arr, int k, int threshold) {
5 | int[] preSum = new int[arr.length + 1];
6 | int res = 0;
7 | for (int i = 1; i < preSum.length; i++) {
8 | preSum[i] = preSum[i - 1] + arr[i - 1];
9 | }
10 | for (int i = k; i < preSum.length; i++) {
11 | if (preSum[i] - preSum[i - k] >= k * threshold)
12 | res++;
13 | }
14 | return res;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/o/OddEvenLinkedList2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.o;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /**
6 | * Created by gaohan on 7/30/18.
7 | */
8 | public class OddEvenLinkedList2 {
9 | public ListNode oddEvenList(ListNode head) {
10 | if (head == null)
11 | return null;
12 | ListNode odd = head, even = head.next, evenHead = even;
13 | while (even != null && even.next != null) {
14 | odd.next = even.next;
15 | odd = odd.next;
16 | even.next = odd.next;
17 | even = odd.next;
18 | }
19 | odd.next = evenHead;
20 | return head;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/o/OddEvenLinkedList3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.o;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /**
6 | * Created by gaohan on 7/30/18.
7 | */
8 | public class OddEvenLinkedList3 {
9 | public ListNode oddEvenList(ListNode head) {
10 | if (head == null)
11 | return null;
12 | ListNode odd = head, even = head.next, evenHead = even;
13 | while (even != null && even.next != null) {
14 | odd.next= even.next;
15 | even.next = odd.next.next;
16 | even = odd.next.next;
17 | odd = odd.next;
18 | even = odd.next;
19 | }
20 | odd.next = evenHead;
21 | return head;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/o/OnebitandTwobitCharacters.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.o;
2 |
3 | public class OnebitandTwobitCharacters {
4 | public boolean isOneBitCharacter(int[] bits) {
5 | int i = 0;
6 | while (i < bits.length - 1) {
7 | if (bits[i] == 0) {
8 | i++;
9 | } else {
10 | i = i + 2;
11 | }
12 |
13 | }
14 | return i == bits.length - 1;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/o/OnebitandTwobitCharacters2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.o;
2 |
3 | public class OnebitandTwobitCharacters2 {
4 | public boolean isOneBitCharacter(int[] bits) {
5 | int i = bits.length - 2;
6 | while (i >= 0 && bits[i] > 0)
7 | i--;
8 | return (bits.length - i) % 2 == 0;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/leetcode/algo/o/OptimalAccountBalancing.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.o;
2 |
3 | public class OptimalAccountBalancing {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PaintFence2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class PaintFence2 {
4 | public static int numWays(int n, int k) {
5 | if (n <= 0 || k <= 0)
6 | return 0;
7 | if (n == 1)
8 | return k;
9 | int[] dp = new int[n];
10 |
11 | // Initializaiton
12 | dp[0] = k;
13 | // Note!!!!! If 2 posts and have same color, the choice is k not the (k-1)*dp[0]
14 | dp[1] = k * (k - 1) + k;
15 | for (int i = 2; i <= n; i++) {
16 | dp[i] = (k - 1) * (dp[i - 1] + dp[i - 2]);
17 | }
18 | // Final state
19 | return dp[n - 1];
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PairsofSongsWithTotalDurationsDivisibleby60.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class PairsofSongsWithTotalDurationsDivisibleby60 {
7 | public int numPairsDivisibleBy60(int[] times) {
8 | int count = 0;
9 | Map map = new HashMap<>();
10 | for (int time : times) {
11 | int t = time % 60;
12 | if (t == 0)
13 | count += map.getOrDefault(t, 0);
14 | else
15 | count += map.getOrDefault(60 - t, 0);
16 | map.put(t, map.getOrDefault(t, 0) + 1);
17 | }
18 | return count;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PalindromeLinkedList2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | public class PalindromeLinkedList2 {
6 | public boolean isPalindrome(ListNode head) {
7 | if (head == null)
8 | return true;
9 | ListNode p = head;
10 | int count = 0;
11 | while (p != null) {
12 | count++;
13 | p = p.next;
14 | }
15 | int nums[] = new int[count];
16 | p = head;
17 | int i = 0;
18 | while (p != null) {
19 | nums[i++] = p.val;
20 | }
21 | for (int j = 0; j < count; j++) {
22 | if (nums[j] != nums[count - j - 1])
23 | return false;
24 | }
25 | return true;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PalindromeNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Determine whether an integer is a Palindrome. Do this without extra space.
4 | *
5 | */
6 | public class PalindromeNumber {
7 | public boolean isPalindrome(int x) {
8 | if (x < 0)
9 | return false;
10 | return reverse(x) == x;
11 | }
12 |
13 | public static int reverse(int x) {
14 | int result = 0;
15 | while (x != 0) {
16 | result = result * 10 + x % 10;
17 | x /= 10;
18 | }
19 | return result;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PalindromePairs.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /**
4 | * Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
5 | *
6 | * Example 1:
7 | *
8 | * Input: ["abcd","dcba","lls","s","sssll"]
9 | * Output: [[0,1],[1,0],[3,2],[2,4]]
10 | * Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
11 | * Example 2:
12 | *
13 | * Input: ["bat","tab","cat"]
14 | * Output: [[0,1],[1,0]]
15 | * Explanation: The palindromes are ["battab","tabbat"]
16 | */
17 | public class PalindromePairs {
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PalindromicSubstrings.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /**
4 | * Given a string, your task is to count how many palindromic substrings in this string.
5 | *
6 | * The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
7 | *
8 | * Example 1:
9 | *
10 | * Input: "abc"
11 | * Output: 3
12 | * Explanation: Three palindromic strings: "a", "b", "c".
13 | *
14 | *
15 | * Example 2:
16 | *
17 | * Input: "aaa"
18 | * Output: 6
19 | * Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
20 | *
21 | *
22 | * Note:
23 | *
24 | * The input string length won't exceed 1000.
25 | */
26 | public class PalindromicSubstrings {
27 | public int countSubstrings(String s) {
28 | return 0;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PancakeSorting.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class PancakeSorting {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PartitionArrayIntoThreePartsWithEqualSum.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import java.util.Arrays;
4 |
5 | public class PartitionArrayIntoThreePartsWithEqualSum {
6 | public boolean canThreePartsEqualSum(int[] A) {
7 | int sum = Arrays.stream(A).sum();
8 | if (sum % 3 != 0)
9 | return false;
10 | int cur = 0, count = 0;
11 | for (int i = 0; i < A.length; i++) {
12 | cur += A[i];
13 | if (cur == sum / 3) {
14 | count++;
15 | cur = 0;
16 | }
17 | }
18 | return count >= 3;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PartitionArrayIntoThreePartsWithEqualSum2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import java.util.Arrays;
4 |
5 | public class PartitionArrayIntoThreePartsWithEqualSum2 {
6 | public boolean canThreePartsEqualSum(int[] A) {
7 | int sum = Arrays.stream(A).sum();
8 | if (sum % 3 != 0)
9 | return false;
10 | int target = sum / 3;
11 | int currentSum = 0, count = 0;
12 | for (int a : A) {
13 | currentSum += a;
14 | if (currentSum == target) {
15 | if (count != 2) {
16 | currentSum = 0;
17 | count++;
18 | }else
19 | return true;
20 | }
21 | }
22 | return false;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PartitionArrayintoDisjointIntervals.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class PartitionArrayintoDisjointIntervals {
4 | public int partitionDisjoint(int[] A) {
5 | int N = A.length;
6 | int[] maxleft = new int[N];
7 | int[] minright = new int[N];
8 |
9 | int curMax = A[0];
10 | for (int i = 0; i < N; i++) {
11 | curMax = Math.max(curMax, A[i]);
12 | maxleft[i] = curMax;
13 | }
14 |
15 | curMax = A[N - 1];
16 | for (int i = N - 1; i >= 0; i--) {
17 | curMax = Math.min(curMax, A[i]);
18 | minright[i] = curMax;
19 | }
20 |
21 | for (int i = 1; i < N; i++)
22 | if (maxleft[i - 1] <= minright[i])
23 | return i;
24 |
25 | throw null;
26 | }
27 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PartitionEqualSubsetSum.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /**
4 | * Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
5 |
6 | Note:
7 | Each of the array element will not exceed 100.
8 | The array size will not exceed 200.
9 | Example 1:
10 |
11 | Input: [1, 5, 11, 5]
12 |
13 | Output: true
14 |
15 | Explanation: The array can be partitioned as [1, 5, 5] and [11].
16 | Example 2:
17 |
18 | Input: [1, 2, 3, 5]
19 |
20 | Output: false
21 |
22 | Explanation: The array cannot be partitioned into equal sum subsets.
23 | */
24 | public class PartitionEqualSubsetSum {
25 | public boolean canPartition(int[] nums) {
26 | return true;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PartitionLabels.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | public class PartitionLabels {
7 | public List partitionLabels(String S) {
8 | int[] last = new int[26];
9 | for (int i = 0; i < S.length(); ++i)
10 | last[S.charAt(i) - 'a'] = i;
11 |
12 | int j = 0, anchor = 0;
13 | List ans = new ArrayList();
14 | for (int i = 0; i < S.length(); ++i) {
15 | j = Math.max(j, last[S.charAt(i) - 'a']);
16 | // Can partition now
17 | if (i == j) {
18 | ans.add(i - anchor + 1);
19 | anchor = i + 1;
20 | }
21 | }
22 | return ans;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PathSum3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | public class PathSum3 {
6 | boolean hasPathSum(TreeNode root, int sum) {
7 | return hasPathSum(root, 0, sum);
8 | }
9 |
10 | boolean hasPathSum(TreeNode root, int sum, int target) {
11 | if (root == null)
12 | return false;
13 | sum += root.val;
14 | // must reach leaf nodes
15 | if (root.left == null && root.right == null) {
16 | return sum == target;
17 | }
18 | return hasPathSum(root.left, sum, target) || hasPathSum(root.right, sum, target);
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PeakIndexinaMountainArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class PeakIndexinaMountainArray {
4 | public int peakIndexInMountainArray(int[] A) {
5 | int i = 0;
6 | while (A[i] < A[i+1]) i++;
7 | return i;
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PeakIndexinaMountainArray2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class PeakIndexinaMountainArray2 {
4 | public int peakIndexInMountainArray(int[] A) {
5 | int lo = 0, hi = A.length - 1;
6 | while (lo < hi) {
7 | int mi = lo + (hi - lo) / 2;
8 | if (A[mi] < A[mi + 1])
9 | lo = mi + 1;
10 | else
11 | hi = mi;
12 | }
13 | return lo;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PerfectNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class PerfectNumber {
4 | public boolean checkPerfectNumber(int num) {
5 | if (num <= 0) {
6 | return false;
7 | }
8 | int sum = 0;
9 | for (int i = 1; i * i <= num; i++) {
10 | if (num % i == 0) {
11 | sum += i;
12 | if (i * i != num) {
13 | sum += num / i;
14 | }
15 |
16 | }
17 | }
18 | return sum - num == num;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PerfectNumber2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class PerfectNumber2 {
4 | public boolean checkPerfectNumber(int num) {
5 |
6 | int sum = 0;
7 | if (num == 0) {
8 | return false;
9 | }
10 | for (int i = 1; i <= num / 2; i++) {
11 | if (num % i == 0) {
12 | sum = sum + i;
13 |
14 | }
15 | }
16 |
17 | return sum == num;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PerfectSquares.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
4 | * For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
5 | */
6 | //TLE
7 | public class PerfectSquares {
8 | public int numSquares(int n) {
9 | int sqrt = (int) Math.sqrt(n);
10 | if (sqrt == 0)
11 | return 0;
12 | int count = 0;
13 | int min = Integer.MAX_VALUE;
14 | for (int i = sqrt; i >= 1; i--) {
15 | count = 1 + numSquares(n - i * i);
16 | if (count < min)
17 | min = count;
18 | }
19 | return min;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PerfectSquares3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 | /* Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
3 | * For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
4 | */
5 | public class PerfectSquares3 {
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PlusOne.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given a non-negative number represented as an array of digits, plus one to the number.
4 | * The digits are stored such that the most significant digit is at the head of the list.
5 | */
6 | public class PlusOne {
7 | public int[] plusOne(int[] digits) {
8 | int carry = 1;
9 | for (int i = digits.length - 1; i >= 0; i--) {
10 | int sum = digits[i] + carry;
11 | digits[i] = sum % 10;
12 | carry = sum / 10;
13 | if (sum < 10)
14 | return digits;
15 | }
16 | if (carry == 1) {
17 | int[] res = new int[digits.length + 1];
18 | res[0] = 1;
19 | for (int i = 1; i < res.length; i++)
20 | res[i] = digits[i - 1];
21 | return res;
22 | }
23 | return digits;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PlusOne2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given a non-negative number represented as an array of digits, plus one to the number.
4 | * The digits are stored such that the most significant digit is at the head of the list.
5 | */
6 | public class PlusOne2 {
7 | public int[] plusOne(int[] digits) {
8 | int carry = 1;
9 | for (int i = digits.length - 1; i >= 0; i--) {
10 | if (digits[i] < 9) {
11 | digits[i] += carry;
12 | return digits;
13 | } else {
14 | digits[i] = 0;
15 | carry = 1;
16 | }
17 | }
18 | // case digits = 999
19 | if (carry == 1) {
20 | int res[] = new int[digits.length + 1];
21 | res[0] = 1;
22 | return res;
23 | }
24 | return digits;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PowerfulIntegers.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import java.util.ArrayList;
4 | import java.util.HashSet;
5 | import java.util.List;
6 | import java.util.Set;
7 |
8 | public class PowerfulIntegers {
9 | public List powerfulIntegers(int x, int y, int bound) {
10 | Set seen = new HashSet();
11 | for (int i = 0; i < 18 && Math.pow(x, i) <= bound; ++i)
12 | for (int j = 0; j < 18 && Math.pow(y, j) <= bound; ++j) {
13 | int v = (int) Math.pow(x, i) + (int) Math.pow(y, j);
14 | if (v <= bound) {
15 | seen.add(v);
16 | }
17 | }
18 |
19 | return new ArrayList(seen);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PowerofFour.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
4 | * Example:
5 | * Given num = 16, return true. Given num = 5, return false.
6 | * Follow up: Could you solve it without loops/recursion?
7 | */
8 | public class PowerofFour {
9 | public boolean isPowerOfFour(int num) {
10 | if (num <= 0)
11 | return false;
12 | while (num != 1) {
13 | if (num % 4 != 0)
14 | return false;
15 | num = num / 4;
16 | }
17 | return true;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PowerofFour2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
4 | * Example:
5 | * Given num = 16, return true. Given num = 5, return false.
6 | * Follow up: Could you solve it without loops/recursion?
7 | */
8 | public class PowerofFour2 {
9 | public boolean isPowerOfFour(int num) {
10 | if (num <= 0)
11 | return false;
12 | if (num == 2)
13 | return false;
14 | int count = 0;
15 | int zeros = 0;
16 | while (num != 0) {
17 | if ((num & 1) == 1)
18 | count++;
19 | else {
20 | zeros++;
21 | }
22 | num = num >> 1;
23 | }
24 | return count == 1 && zeros % 2 == 0;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PowerofThree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given an integer, write a function to determine if it is a power of three.
4 | * Follow up:
5 | * Could you do it without using any loop / recursion?
6 | */
7 | public class PowerofThree {
8 | public boolean isPowerOfThree(int n) {
9 | if (n <= 0)
10 | return false;
11 | while (n % 3 == 0) {
12 | n /= 3;
13 | }
14 | return n == 1 ? true : false;
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PowerofThree2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given an integer, write a function to determine if it is a power of three.
4 | * Follow up:
5 | * Could you do it without using any loop / recursion?
6 | */
7 | public class PowerofThree2 {
8 | public boolean isPowerOfThree(int n) {
9 | return n > 0 && 1162261467 % n == 0;
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PowerofTwo.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Given an integer, write a function to determine if it is a power of two
4 | *
5 | */
6 | public class PowerofTwo {
7 | public boolean isPowerOfTwo(int n) {
8 | if (n <= 0)
9 | return false;
10 | while (n % 2 == 0) {
11 | n /= 2;
12 | }
13 | return n == 1 ? true : false;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PowerofTwo2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 | /* Given an integer, write a function to determine if it is a power of two
3 | *
4 | */
5 | public class PowerofTwo2 {
6 | public boolean isPowerOfTwo(int n) {
7 | if (n == 1)
8 | return true;
9 | if (n == 0)
10 | return false;
11 | while (n != 1) {
12 | if ((n & 1) != 0)
13 | return false;
14 | n = n >> 1;
15 | }
16 | return true;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/Powxn.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 | /* Implement pow(x, n).
3 | */
4 | public class Powxn {
5 | public double myPow(double x, int n) {
6 | if (n == 0)
7 | return 1.0;
8 | if (x == 0.)
9 | return 0.0;
10 | if (n < 0) {
11 | n = -n;
12 | x = 1. / x;
13 | }
14 | double temp = myPow(x, n / 2);
15 | return n % 2 == 0 ? temp * temp : temp * temp * x;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/Powxn2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /*Implement pow(x, n).
4 | */
5 | public class Powxn2 {
6 | public double myPow(double x, int n) {
7 | if (n == 0)
8 | return 1.0;
9 | if (n == 2)
10 | return x * x;
11 | if (n < 0) {
12 | n = -n;
13 | x = 1.0 / x;
14 | }
15 | if (n % 2 == 0)
16 | return myPow(myPow(x, n / 2), 2);
17 | else
18 | return x * myPow(myPow(x, n / 2), 2);
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/Powxn3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /* Implement pow(x, n).
4 | */
5 | public class Powxn3 {
6 | public double myPow(double x, int n) {
7 | if (n == 0)
8 | return 1.;
9 | if (x == 0)
10 | return 0.;
11 | if (n < 0) {
12 | n = -n;
13 | x = 1. / x;
14 | }
15 |
16 | double res = 1.0;
17 | while (n > 0) {
18 | if (n % 2 == 1)
19 | res *= x;
20 | x *= x;
21 | n >>= 1;
22 | }
23 | return res;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PrintImmutableLinkedListinReverse.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | import leetcode.common.ImmutableListNode;
4 |
5 | public class PrintImmutableLinkedListinReverse {
6 | /**
7 | * // This is the ImmutableListNode's API interface.
8 | * // You should not implement it, or speculate about its implementation.
9 | * interface ImmutableListNode {
10 | * public void printValue(); // print the value of this node.
11 | * public ImmutableListNode getNext(); // return the next node.
12 | * };
13 | */
14 |
15 | public void printLinkedListInReverse(ImmutableListNode head) {
16 | if (head == null)
17 | return;
18 | else {
19 | printLinkedListInReverse(head.getNext());
20 | head.printValue();
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/ProjectionAreaof3DShapes.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | public class ProjectionAreaof3DShapes {
4 | public int projectionArea(int[][] grid) {
5 | int area = 0;
6 | for (int i = 0; i < grid.length; i++) {
7 | int max = 0;
8 | for (int j = 0; j < grid[0].length; j++) {
9 | if (grid[i][j] != 0)
10 | area++;
11 | max = Math.max(max, grid[i][j]);
12 | }
13 | area += max;
14 | }
15 | for (int j = 0; j < grid[0].length; j++) {
16 | int max = 0;
17 | for (int i = 0; i < grid.length; i++) {
18 | max = Math.max(max, grid[i][j]);
19 | }
20 | area += max;
21 | }
22 | return area;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/p/PushDominoes2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.p;
2 |
3 | /**
4 | * Created by gaohan on 5/27/18.
5 | */
6 | public class PushDominoes2 {
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RandomFlipMatrix.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 | import java.util.Random;
6 |
7 | public class RandomFlipMatrix {
8 | Map V = new HashMap<>();
9 | int nr, nc, rem;
10 | Random rand = new Random();
11 |
12 | public RandomFlipMatrix(int n_rows, int n_cols) {
13 | nr = n_rows;
14 | nc = n_cols;
15 | rem = nr * nc;
16 | }
17 |
18 | public int[] flip() {
19 | int r = rand.nextInt(rem--);
20 | int x = V.getOrDefault(r, r);
21 | V.put(r, V.getOrDefault(rem, rem));
22 | return new int[]{x / nc, x % nc};
23 | }
24 |
25 | public void reset() {
26 | V.clear();
27 | rem = nr * nc;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RandomListNode.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | public class RandomListNode {
4 | public int label;
5 | public RandomListNode next, random;
6 |
7 | public RandomListNode(int x) {
8 | this.label = x;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RangeAdditionII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | public class RangeAdditionII {
4 | public int maxCount(int m, int n, int[][] ops) {
5 | for (int[] op : ops) {
6 | m = Math.min(m, op[0]);
7 | n = Math.min(n, op[1]);
8 | }
9 | return m * n;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RansomNote.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import java.util.HashMap;
4 |
5 | public class RansomNote {
6 | public boolean canConstruct(String ransomNote, String magazine) {
7 |
8 | HashMap map = new HashMap();
9 |
10 | for (int i = 0; i < magazine.length(); i++) {
11 | if (null != map.get(magazine.charAt(i)))
12 | map.put(magazine.charAt(i), map.get(magazine.charAt(i)) + 1);
13 | else
14 | map.put(magazine.charAt(i), 1);
15 |
16 | }
17 |
18 | for (int i = 0; i < ransomNote.length(); i++) {
19 | if (null == map.get(ransomNote.charAt(i)) || 0 == map.get(ransomNote.charAt(i))) {
20 | return false;
21 | } else
22 | map.put(ransomNote.charAt(i), map.get(ransomNote.charAt(i)) - 1);
23 |
24 | }
25 | return true;
26 | }
27 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RansomNote2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /*
7 | * Given an random
8 | */
9 | public class RansomNote2 {
10 | public boolean canConstruct(String ransomNote, String magazine) {
11 | Map magM = new HashMap<>();
12 | for (char c : magazine.toCharArray()) {
13 | int newCount = magM.getOrDefault(c, 0) + 1;
14 | magM.put(c, newCount);
15 | }
16 | for (char c : ransomNote.toCharArray()) {
17 | int newCount = magM.getOrDefault(c, 0) - 1;
18 | if (newCount < 0)
19 | return false;
20 | magM.put(c, newCount);
21 | }
22 | return true;
23 | }
24 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RectangleAreaII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /**
4 | * Created by gaohan on 6/10/18.
5 | */
6 | public class RectangleAreaII {
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveDuplicateLetters.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 | /* Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once.
3 | * You must make sure your result is the smallest in lexicographical order among all possible results.
4 | * Example:
5 | * Given "bcabc"
6 | * Return "abc"
7 | * Given "cbacdcbc"
8 | * Return "acdb"
9 | */
10 | public class RemoveDuplicateLetters {
11 |
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveDuplicatesfromSortedArray2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 | /* Given a sorted array, remove the duplicates in place such that each element appear only
3 | * once and return the new length.
4 | * Do not allocate extra space for another array, you must do this in place with constant memory.
5 | * For example:
6 | * Given input array A = [1,1,2], Your function should return length = 2, and A is now [1,2].
7 | */
8 | public class RemoveDuplicatesfromSortedArray2 {
9 |
10 | public static int removeDuplicates(int[] A) {
11 | int count = 0;
12 | int len = A.length;
13 | for (int i = 0; i < len; i++) {
14 | if (count == 0 || A[i] != A[count - 1]) {
15 | A[count++] = A[i];
16 | }
17 | }
18 | return count;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveDuplicatesfromSortedArrayII2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /* Follow up for "Remove Duplicates":
4 | * What if duplicates are allowed at most twice?
5 | * For example:
6 | * Given sorted array A = [1,1,1,2,2,3],
7 | * Your function should return length = 5, and A is now [1,1,2,2,3].
8 | */
9 | public class RemoveDuplicatesfromSortedArrayII2 {
10 | public int removeDuplicates(int[] A) {
11 | if (A.length <= 2)
12 | return A.length;
13 | int prev = 1; // point to previous
14 | int curr = 2; // point to current
15 | while (curr < A.length) {
16 | if (A[curr] == A[prev] && A[curr] == A[prev - 1]) {
17 | curr++;
18 | } else {
19 | prev++;
20 | A[prev] = A[curr];
21 | curr++;
22 | }
23 | }
24 | return prev + 1;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveDuplicatesfromSortedList2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /* Given a sorted linked list, delete all duplicates such that each element appear only once.
6 | * For example,
7 | * Given 1->1->2, return 1->2.
8 | * Given 1->1->2->3->3, return 1->2->3.
9 | */
10 | // One pointer
11 | public class RemoveDuplicatesfromSortedList2 {
12 | public ListNode deleteDuplicates(ListNode head) {
13 | if (head == null || head.next == null)
14 | return head;
15 |
16 | ListNode p = head;
17 | while (p != null && p.next != null) {
18 | if (p.val == p.next.val) {
19 | p.next = p.next.next;
20 | } else {
21 | p = p.next;
22 | }
23 | }
24 |
25 | return head;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveDuplicatesfromSortedListII3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | public class RemoveDuplicatesfromSortedListII3 {
6 | public ListNode deleteDuplicates(ListNode head) {
7 | if (head == null || head.next == null)
8 | return head;
9 |
10 | ListNode dummy = new ListNode(0);
11 | dummy.next = head;
12 | head = dummy;
13 |
14 | while (head.next != null && head.next.next != null) {
15 | if (head.next.val == head.next.next.val) {
16 | int val = head.next.val;
17 | while (head.next != null && head.next.val == val) {
18 | head.next = head.next.next;
19 | }
20 | } else {
21 | head = head.next;
22 | }
23 | }
24 |
25 | return dummy.next;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveElement.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /* Given an array and a value, remove all instances of that value in place and return the new length.
4 | * The order of elements can be changed. It doesn't matter what you leave beyond the new length
5 | */
6 | public class RemoveElement {
7 | public int removeElement(int[] A, int elem) {
8 | int begin = 0;
9 | int end = A.length - 1;
10 | while (begin <= end) {
11 | if (A[begin] != elem)
12 | begin++;
13 | else if (A[end] == elem)
14 | end--;
15 | else
16 | A[begin++] = A[end--];
17 | }
18 | return begin;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveLinkedListElements2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | public class RemoveLinkedListElements2 {
6 | public ListNode removeElements(ListNode head, int val) {
7 | if (head == null) return null;
8 | head.next = removeElements(head.next, val);
9 | return head.val == val ? head.next : head;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemoveNthNodeFromEndofList.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | public class RemoveNthNodeFromEndofList {
6 | public ListNode removeNthFromEnd(ListNode head, int n) {
7 | ListNode first = head;
8 | ListNode second = head;
9 | if (head.next == null)
10 | return null;
11 | while (n != 0) {
12 | first = first.next;
13 | n--;
14 | }
15 | if (first == null)
16 | return head.next;
17 | while (first.next != null) {
18 | first = first.next;
19 | second = second.next;
20 | }
21 | second.next = second.next.next;
22 | return head;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RemovePalindromicSubsequences.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | public class RemovePalindromicSubsequences {
4 | public int removePalindromeSub(String s) {
5 | if (s.length() == 0)
6 | return 0;
7 |
8 | // check if s is palindromic
9 | boolean isPalindromic = true;
10 | int left = 0;
11 | int right = s.length() - 1;
12 | for (; left < right; left++, right--)
13 | if (s.charAt(left) != s.charAt(right)) {
14 | isPalindromic = false;
15 | break;
16 | }
17 |
18 | return isPalindromic ? 1 : 2;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReshapetheMatrix2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 |
6 | public class ReshapetheMatrix2 {
7 | public int[][] matrixReshape(int[][] nums, int r, int c) {
8 | int[][] res = new int[r][c];
9 | if (nums.length == 0 || r * c != nums.length * nums[0].length)
10 | return nums;
11 | int rows = 0, cols = 0;
12 | for (int i = 0; i < nums.length; i++) {
13 | for (int j = 0; j < nums[0].length; j++) {
14 | res[rows][cols] = nums[i][j];
15 | cols++;
16 | if (cols == c) {
17 | rows++;
18 | cols = 0;
19 | }
20 | }
21 | }
22 | return res;
23 | }
24 | }
25 |
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReverseBits.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /* Reverse bits of a given 32 bits unsigned integer.
4 | * For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
5 | * return 964176192 (represented in binary as 00111001011110000010100101000000).
6 | * Follow up:
7 | * If this function is called many times, how would you optimize it?
8 | */
9 | public class ReverseBits {
10 | public int reverseBits(int n) {
11 | int res = 0;
12 | int bit = 0;
13 | for (int i = 0; i < 32; i++) {
14 | bit = n & (1 << i);
15 | if (bit != 0)
16 | res = res + (1 << (31 - i));
17 | }
18 | return res;
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReverseInteger2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | public class ReverseInteger2 {
4 | public int reverse(int x) {
5 | StringBuilder num = new StringBuilder();
6 | int val;
7 |
8 | if (x > 0) {
9 | num = num.append(x).reverse();
10 | try {
11 | val = Integer.parseInt(num.toString());
12 | } catch (NumberFormatException e) {
13 | return 0;
14 | }
15 |
16 | return val;
17 | }
18 |
19 | else {
20 | x = -x;
21 | num = num.append(x).reverse();
22 | try {
23 | val = Integer.parseInt(num.toString());
24 | } catch (NumberFormatException e) {
25 | return 0;
26 | }
27 | return -val;
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReverseLinkedList.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /* Reverse a singly linked list.
6 | */
7 | public class ReverseLinkedList {
8 |
9 | public ListNode reverseList(ListNode head) {
10 | if (head == null)
11 | return head;
12 | ListNode p = head;
13 | ListNode curr = head.next;
14 | head.next = null;
15 | while (curr != null) {
16 | ListNode next = curr.next;
17 | curr.next = p;
18 | p = curr;
19 | curr = next;
20 | }
21 | return p;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReverseLinkedList2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /* Reverse a singly linked list.
6 | */
7 | /* recursive solution
8 | *
9 | */
10 | public class ReverseLinkedList2 {
11 |
12 | public ListNode reverseList(ListNode head) {
13 | if (head == null)
14 | return head;
15 | if(head.next==null)
16 | return head;
17 | ListNode newHead = reverseList(head.next);
18 | head.next.next=head;
19 | head.next=null;
20 | return newHead;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReversePairs.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /**
4 | *Given an array nums, we call (i, j) an important reverse pair if i < j and nums[i] > 2*nums[j].
5 |
6 | You need to return the number of important reverse pairs in the given array.
7 |
8 | Example1:
9 |
10 | Input: [1,3,2,3,1]
11 | Output: 2
12 | Example2:
13 |
14 | Input: [2,4,3,5,1]
15 | Output: 3
16 | Note:
17 | The length of the given array will not exceed 50,000.
18 | All the numbers in the input array are in the range of 32-bit integer.
19 |
20 | */
21 | public class ReversePairs {
22 | public int reversePairs(int[] nums) {
23 | return 0;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReverseString.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | public class ReverseString {
4 | public String reverseString(String s) {
5 | char[] chars = s.toCharArray();
6 | int i = 0, j = s.length() - 1;
7 | while (i < j) {
8 | char tmp = chars[i];
9 | chars[i] = chars[j];
10 | chars[j] = tmp;
11 | i++;
12 | j--;
13 | }
14 | return new String(chars);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/ReverseVowelsofaString2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | public class ReverseVowelsofaString2 {
4 | public static String reverseVowels(String s) {
5 | if (s == null)
6 | return "";
7 | char chars[] = s.toCharArray();
8 | int i = 0, j = s.length() - 1;
9 | while (i <= j) {
10 | while (i < s.length() - 1 && !isvowel(s.charAt(i)))
11 | i++;
12 | while (j >= 0 && !isvowel(s.charAt(j)))
13 | j--;
14 | if (i < s.length() && j >= 0) {
15 | chars[i] = s.charAt(j);
16 | chars[j] = s.charAt(i);
17 | i++;
18 | j--;
19 | }
20 | }
21 | return new String(chars);
22 | }
23 |
24 | private static boolean isvowel(char c) {
25 | int pos = "aeiouAEIOU".indexOf(c);
26 | return pos >= 0;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RomantoInteger2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | /* Given a Roman numeral, convert it to an integer.
7 | * Input is guaranteed to be within the range from 1 to 3999.
8 | */
9 | public class RomantoInteger2 {
10 | public int romanToInt(String s) {
11 | Map map = new HashMap();
12 | map.put('I', 1);
13 | map.put('V', 5);
14 | map.put('X', 10);
15 | map.put('L', 50);
16 | map.put('C', 100);
17 | map.put('D', 500);
18 | map.put('M', 1000);
19 | int prev = 0, total = 0;
20 | for (char c : s.toCharArray()) {
21 | int curr = map.get(c);
22 | total += (curr > prev) ? (curr - 2 * prev) : curr;
23 | prev = curr;
24 | }
25 | return total;
26 | }
27 | }
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RotateArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /* Rotate an array of n elements to the right by k steps.
4 | * 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].
5 | * Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
6 | */
7 | // Space: O(n)
8 | // Time: O(n)
9 | public class RotateArray {
10 | public void rotate(int[] nums, int k) {
11 | int len = nums.length;
12 | k = k % len;
13 | int[] res = new int[len];
14 | int index = 0;
15 | for (int i = len - k; i < len; i++) {
16 | res[index++] = nums[i];
17 | }
18 | for (int i = 0; i < len - k; i++) {
19 | res[index++] = nums[i];
20 | }
21 | for (int i = 0; i < len; i++) {
22 | nums[i] = res[i];
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RotateArray2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /* Rotate an array of n elements to the right by k steps.
4 | * 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].
5 | * Note: Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
6 | */
7 | // O(k^2)
8 | public class RotateArray2 {
9 | public void rotate(int[] nums, int k) {
10 | int len = nums.length;
11 | k = k % len;
12 | int temp = 0;
13 | for (int i = len - k; i < len; i++) {
14 | temp = nums[i];
15 | for (int j = i - 1; j >= i - len + k; j--) {
16 | nums[j + 1] = nums[j];
17 | }
18 | nums[i - len + k] = temp;
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/r/RotateString.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.r;
2 |
3 | /**
4 | * We are given two strings, A and B.
5 | *
6 | * A shift on A consists of taking string A and moving the leftmost character to the rightmost position. For example, if A = 'abcde', then it will be 'bcdea' after one shift on A. Return True if and only if A can become B after some number of shifts on A.
7 | *
8 | * Example 1:
9 | * Input: A = 'abcde', B = 'cdeab'
10 | * Output: true
11 | *
12 | * Example 2:
13 | * Input: A = 'abcde', B = 'abced'
14 | * Output: false
15 | * Note:
16 | *
17 | * A and B will have length at most 100.
18 | */
19 | public class RotateString {
20 | public boolean rotateString(String A, String B) {
21 | return A.length() == B.length() && (A + A).contains(B);
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SameTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | /* Given two binary trees, write a function to check if they are equal or not.
6 | * Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
7 | */
8 | public class SameTree {
9 | public boolean isSameTree(TreeNode p, TreeNode q) {
10 | if (p == null && q != null || p != null && q == null)
11 | return false;
12 | if (p == null && q == null)
13 | return true;
14 | if (p.val == q.val)
15 | return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
16 | else
17 | return false;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/ScrambleString2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class ScrambleString2 {
4 | /*简单的说,就是s1和s2是scramble的话,那么必然存在一个在s1上的长度l1,将s1分成s11和s12两段,同样有s21和s22。
5 | 那么要么s11和s21是scramble的并且s12和s22是scramble的;
6 | 要么s11和s22是scramble的并且s12和s21是scramble的。*/
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SearchInsertPosition2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SearchInsertPosition2 {
4 | public int searchInsert(int[] A, int target) {
5 | int start=0, end=A.length-1;
6 | return searchInsert(A,start,end,target);
7 | }
8 |
9 | public int searchInsert(int[] A, int start, int end,int target){
10 | if(start>=end){
11 | if(A[start]>1;
17 | if(A[mid]==target)
18 | return mid;
19 | if(A[mid]>target)
20 | return searchInsert(A,start,mid,target);
21 | else
22 | return searchInsert(A,mid+1,end,target);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SearchSuggestionsSystem.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | import java.util.List;
4 |
5 | public class SearchSuggestionsSystem {
6 | public List> suggestedProducts(String[] products, String searchWord) {
7 | return null;
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SearchinaBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | public class SearchinaBinarySearchTree {
6 | public TreeNode searchBST(TreeNode root, int val) {
7 | if (root == null)
8 | return null;
9 |
10 | if (root.val == val)
11 | return root;
12 | else if (val < root.val)
13 | return searchBST(root.left, val);
14 | else
15 | return searchBST(root.right, val);
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SecondMinimumNodeInaBinaryTree2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | public class SecondMinimumNodeInaBinaryTree2 {
6 |
7 | int min1;
8 | int ans = Integer.MAX_VALUE;
9 |
10 | public int findSecondMinimumValue(TreeNode root) {
11 | min1 = root.val;
12 | dfs(root);
13 | return ans < Integer.MAX_VALUE ? ans : -1;
14 | }
15 |
16 | public void dfs(TreeNode root) {
17 | if (root == null)
18 | return;
19 | if (min1 < root.val && root.val < ans) {
20 | ans = root.val;
21 | } else if (min1 == root.val) {
22 | dfs(root.left);
23 | dfs(root.right);
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SimilarStringGroups.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /**
4 | * Created by gaohan on 5/26/18.
5 | */
6 | public class SimilarStringGroups {
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SingleElementinaSortedArray.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SingleElementinaSortedArray {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SingleNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /* Given an array of integers, every element appears twice except for one. Find that single one.
4 | * Note:
5 | * Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
6 | */
7 | public class SingleNumber {
8 | public int singleNumber(int[] A) {
9 | int len = A.length;
10 | if (len == 0)
11 | return 0;
12 | int record = A[0];
13 | for (int i = 1; i < len; i++)
14 | record = record ^ A[i];
15 | return record;
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SortArrayByParityII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SortArrayByParityII {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SortArrayByParityII2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SortArrayByParityII2 {
4 | public int[] sortArrayByParityII(int[] A) {
5 | int j = 1;
6 | for (int i = 0; i < A.length; i += 2) {
7 | if (A[i] % 2 == 1) {
8 | while (j < A.length) {
9 | if (A[j] % 2 == 0) {
10 | swap(A, j, i);
11 | break;
12 | }
13 | j += 2;
14 | }
15 | }
16 | }
17 | return A;
18 | }
19 |
20 | public void swap(int[] A, int j, int i) {
21 | int temp = A[j];
22 | A[j] = A[i];
23 | A[i] = temp;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SortArrayByParityII3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SortArrayByParityII3 {
4 | public int[] sortArrayByParityII(int[] A) {
5 | int j = 1;
6 | for (int i = 0; i < A.length; i += 2) {
7 | if (A[i] % 2 == 1) {
8 | while (A[j] % 2 != 0) {
9 | j += 2;
10 | }
11 | swap(A, j, i);
12 | }
13 | }
14 | return A;
15 | }
16 |
17 | public void swap(int[] A, int j, int i) {
18 | int temp = A[j];
19 | A[j] = A[i];
20 | A[i] = temp;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SplitBST.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SplitBST {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/Sqrtx.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 | /* Implement int sqrt(int x).
3 | * Compute and return the square root of x.
4 | */
5 | /* 二分搜索
6 | * 对于一个非负数n,它的平方根不会大于(n/2+1)
7 | * 在[0, n/2+1]这个范围内可以进行二分搜索,求出n的平方根。
8 | */
9 | public class Sqrtx {
10 | public int sqrt(int x) {
11 | int left = 0;
12 | int right = x / 2 + 1;
13 | while (left <= right) {
14 | int mid = (left + right) >> 1;
15 | if ((long) mid * mid == x)
16 | return mid;
17 | else if ((long) mid * mid > x)
18 | right = mid - 1;
19 | else
20 | left = mid + 1;
21 | }
22 | return left - 1;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/Sqrtx2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 | /* Implement int sqrt(int x).
3 | * Compute and return the square root of x.
4 | */
5 | /* 牛顿迭代法
6 | * 经过(xi, f(xi))的切线方程为f(x)=f(xi)+f’(xi)(x-xi),其中f'(x)为f(x)的导数2x。
7 | * 令切线方程等于0,即可求出xi+1=xi-f(xi)/f'(xi)。
8 | * 化简,xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。
9 | */
10 |
11 | public class Sqrtx2 {
12 | public int sqrt(int x) {
13 | if (x == 0) return 0;
14 | double last = 0;
15 | double res = 1;
16 | while (res != last)
17 | {
18 | last = res;
19 | res = (res + x / res) / 2;
20 | }
21 | return (int)res;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/StudentAttendanceRecordI3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /**
4 | * You are given a string representing an attendance record for a student. The record only contains the following three characters:
5 | * 'A' : Absent.
6 | * 'L' : Late.
7 | * 'P' : Present.
8 | * A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).
9 | *
10 | * You need to return whether the student could be rewarded according to his attendance record.
11 | *
12 | * Example 1:
13 | * Input: "PPALLP"
14 | * Output: True
15 | * Example 2:
16 | * Input: "PPALLL"
17 | * Output: False
18 | */
19 | public class StudentAttendanceRecordI3 {
20 | public boolean checkRecord(String s) {
21 | return !s.matches(".*(A.*A|LLL).*");
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SubsetsII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 | /*
3 | * Given a collection of integers that might contain duplicates, S, return all possible subsets.
4 | * Note:
5 | * Elements in a subset must be in non-descending order.
6 | * The solution set must not contain duplicate subsets.
7 | * For example,
8 | * If S = [1,2,2], a solution is:
9 | * [
10 | * [2],
11 | * [1],
12 | * [1,2,2],
13 | * [2,2],
14 | * [1,2],
15 | * []
16 | * ]
17 | */
18 | public class SubsetsII {
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofDigitsintheMinimumNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SumofDigitsintheMinimumNumber {
4 | public int sumOfDigits(int[] A) {
5 | int min = Integer.MAX_VALUE;
6 | for (int each : A) {
7 | min = Math.min(min, each);
8 | }
9 | int sum = 0;
10 | for (char c : String.valueOf(min).toCharArray()) {
11 | sum += Integer.valueOf(c);
12 | }
13 | /*
14 | while(min!=0) {
15 | sum += min%10;
16 | min/=10;
17 | }
18 | */
19 | return sum % 2 == 0 ? 1 : 0;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofEvenNumbersAfterQueries2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 |
4 | import java.util.Arrays;
5 |
6 | public class SumofEvenNumbersAfterQueries2 {
7 | public int[] sumEvenAfterQueries(int[] A, int[][] queries) {
8 | int S = Arrays.stream(A).filter(x-> x%2==0).sum();
9 | int[] ans = new int[queries.length];
10 |
11 | for (int i = 0; i < queries.length; ++i) {
12 | int val = queries[i][0], index = queries[i][1];
13 | if (A[index] % 2 == 0) S -= A[index];
14 | A[index] += val;
15 | if (A[index] % 2 == 0) S += A[index];
16 | ans[i] = S;
17 | }
18 |
19 | return ans;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofSquareNumbers.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /**
4 | * Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
5 | *
6 | * Example 1:
7 | *
8 | * Input: 5
9 | * Output: True
10 | * Explanation: 1 * 1 + 2 * 2 = 5
11 | *
12 | *
13 | * Example 2:
14 | *
15 | * Input: 3
16 | * Output: False
17 | */
18 | //tle
19 | public class SumofSquareNumbers {
20 | public boolean judgeSquareSum(int c) {
21 | for (long a = 0; a * a <= c; a++) {
22 | for (long b = 0; b * b <= c; b++) {
23 | if (a * a + b * b == c)
24 | return true;
25 | }
26 | }
27 | return false;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofSquareNumbers2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /**
4 | * Given a non-negative integer c, your task is to decide whether there're two integers a and b such that a2 + b2 = c.
5 | *
6 | * Example 1:
7 | *
8 | * Input: 5
9 | * Output: True
10 | * Explanation: 1 * 1 + 2 * 2 = 5
11 | *
12 | *
13 | * Example 2:
14 | *
15 | * Input: 3
16 | * Output: False
17 | */
18 | public class SumofSquareNumbers2 {
19 | public boolean judgeSquareSum(int c) {
20 | for (long a = 0; a * a <= c; a++) {
21 | double b = Math.sqrt(c - a * a);
22 | if (b == (int) b)
23 | return true;
24 | }
25 | return false;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofSubarrayMinimums.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /**
4 | * Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.
5 | *
6 | * Since the answer may be large, return the answer modulo 10^9 + 7.
7 | *
8 | *
9 | *
10 | * Example 1:
11 | *
12 | * Input: [3,1,2,4]
13 | * Output: 17
14 | * Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4].
15 | * Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17.
16 | *
17 | *
18 | * Note:
19 | *
20 | * 1 <= A.length <= 30000
21 | * 1 <= A[i] <= 30000
22 | */
23 | public class SumofSubarrayMinimums {
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofTwoIntegers.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /*Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
4 |
5 | Example:
6 | Given a = 1 and b = 2, return 3.
7 | */
8 | public class SumofTwoIntegers {
9 | public int getSum(int a, int b) {
10 | int res = 0;
11 | int count = 0;
12 | int xor = 1;
13 | while (a != 0 || b != 0 || count != 0) {
14 | if ((a & 1) == 1 && (b & 1) == 1) {
15 | res = count == 0 ? res ^ 0 : res ^ xor;
16 | count = 1;
17 | }
18 | if ((a & 1) == 0 && (b & 1) == 0) {
19 | res = count == 0 ? res ^ 0 : res ^ xor;
20 | count = 0;
21 | } else {
22 | res = count == 0 ? res ^ xor : res ^ 0;
23 | }
24 | xor <<= 1;
25 | a >>>= 1;
26 | b >>>= 1;
27 | }
28 | return res;
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofTwoIntegers2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /*Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
4 |
5 | Example:
6 | Given a = 1 and b = 2, return 3.
7 | */
8 | public class SumofTwoIntegers2 {
9 | // Iterative
10 | public int getSum(int a, int b) {
11 | if (a == 0)
12 | return b;
13 | if (b == 0)
14 | return a;
15 |
16 | while (b != 0) {
17 | int carry = a & b;
18 | a = a ^ b;
19 | b = carry << 1;
20 | }
21 | return a;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SumofTwoIntegers3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /*Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
4 |
5 | Example:
6 | Given a = 1 and b = 2, return 3.
7 | */
8 | public class SumofTwoIntegers3 {
9 |
10 | // Recursive
11 | public int getSum(int a, int b) {
12 | return (b == 0) ? a : getSum(a ^ b, (a & b) << 1);
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SuperEggDrop.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | /**
4 | * 887. Possible Bipartition
5 | */
6 | public class SuperEggDrop {
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SuperUglyNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | public class SuperUglyNumber {
4 | public int nthSuperUglyNumber(int n, int[] primes) {
5 | int[] nums = new int[1690];
6 | nums[0] = 1;
7 | int ugly, i2 = 0, i3 = 0, i5 = 0;
8 |
9 | for (int i = 1; i < 1690; ++i) {
10 | ugly = Math.min(Math.min(nums[i2] * 2, nums[i3] * 3), nums[i5] * 5);
11 | nums[i] = ugly;
12 |
13 | if (ugly == nums[i2] * 2) {
14 | i2++;
15 | }
16 | if (ugly == nums[i3] * 3) {
17 | i3++;
18 | }
19 | if (ugly == nums[i5] * 5) {
20 | i5++;
21 | }
22 | }
23 | return nums[n - 1];
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/s/SwapNodesInPairs3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.s;
2 |
3 | import leetcode.common.ListNode;
4 |
5 | /* Given a linked list, swap every two adjacent nodes and return its head.
6 | * For example,Given 1->2->3->4, you should return the list as 2->1->4->3.
7 | * Your algorithm should use only constant space. You may not modify the
8 | * values in the list, only nodes itself can be changed.
9 | */
10 | /* recursion solution
11 | */
12 | public class SwapNodesInPairs3 {
13 | public ListNode swapPairs(ListNode head) {
14 | if (head == null || head.next == null)
15 | return head;
16 |
17 | ListNode p = head, q = head.next;
18 | p.next = swapPairs(q.next);
19 | head = q;
20 | q.next = p;
21 | return head;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/TheEarliestMomentWhenEveryoneBecomeFriends.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | public class TheEarliestMomentWhenEveryoneBecomeFriends {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/TheMazeII.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | public class TheMazeII {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/ToeplitzMatrix.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | import java.util.HashMap;
4 | import java.util.Map;
5 |
6 | public class ToeplitzMatrix {
7 | public boolean isToeplitzMatrix(int[][] matrix) {
8 | Map groups = new HashMap();
9 | for (int r = 0; r < matrix.length; r++) {
10 | for (int c = 0; c < matrix[0].length; c++) {
11 | if (!groups.containsKey(r - c))
12 | groups.put(r - c, matrix[r][c]);
13 | else if (groups.get(r - c) != matrix[r][c])
14 | return false;
15 | }
16 | }
17 | return true;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/ToeplitzMatrix2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | public class ToeplitzMatrix2 {
4 | public boolean isToeplitzMatrix(int[][] matrix) {
5 | for (int r = 0; r < matrix.length; r++) {
6 | for (int c = 0; c < matrix[0].length; c++) {
7 | if (r > 0 && c > 0 && matrix[r - 1][c - 1] != matrix[r][c]) {
8 | return false;
9 | }
10 | }
11 |
12 | }
13 | return true;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/TotalHammingDistance.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | /**
4 | * The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
5 |
6 | Now your job is to find the total Hamming distance between all pairs of the given numbers.
7 |
8 | Example:
9 | Input: 4, 14, 2
10 |
11 | Output: 6
12 |
13 | Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
14 | showing the four bits relevant in this case). So the answer will be:
15 | HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
16 | Note:
17 | Elements of the given array are in the range of 0 to 10^9
18 | Length of the array will not exceed 10^4.
19 | */
20 | public class TotalHammingDistance {
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/TrimaBinarySearchTree.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | public class TrimaBinarySearchTree {
6 | public TreeNode trimBST(TreeNode root, int L, int R) {
7 | if (root == null)
8 | return root;
9 | if (root.val > R)
10 | return trimBST(root.left, L, R);
11 | if (root.val < L)
12 | return trimBST(root.right, L, R);
13 |
14 | root.left = trimBST(root.left, L, R);
15 | root.right = trimBST(root.right, L, R);
16 | return root;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/TwoSumII2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | public class TwoSumII2 {
4 | public int[] twoSum(int[] numbers, int target) {
5 | // Assume input is already sorted.
6 | int i = 0, j = numbers.length - 1;
7 | while (i < j) {
8 | int sum = numbers[i] + numbers[j];
9 | if (sum < target) {
10 | i++;
11 | } else if (sum > target) {
12 | j--;
13 | } else {
14 | return new int[] { i + 1, j + 1 };
15 | }
16 | }
17 | throw new IllegalArgumentException("No two sum solution");
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/TwoSumIVInputisaBST.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | import leetcode.common.TreeNode;
4 |
5 | import java.util.HashSet;
6 | import java.util.Set;
7 |
8 | public class TwoSumIVInputisaBST {
9 | public boolean findTarget(TreeNode root, int k) {
10 | Set < Integer > set = new HashSet();
11 | return find(root, k, set);
12 | }
13 | public boolean find(TreeNode root, int k, Set< Integer > set) {
14 | if (root == null)
15 | return false;
16 | if (set.contains(k - root.val))
17 | return true;
18 | set.add(root.val);
19 | return find(root.left, k, set) || find(root.right, k, set);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/t/TwoSumLessThanK.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.t;
2 |
3 | import java.util.Arrays;
4 |
5 | public class TwoSumLessThanK {
6 | public int twoSumLessThanK(int[] A, int K) {
7 | if (A.length < 2)
8 | return -1;
9 | int res = Integer.MIN_VALUE;
10 | Arrays.sort(A);
11 |
12 | int low = 0;
13 | int high = A.length - 1;
14 |
15 | while (low < high) {
16 | int sum = A[low] + A[high];
17 | if (sum < K) {
18 | res = Math.max(res, sum);
19 | low++;
20 | } else {
21 | high--;
22 | }
23 | }
24 | return res == Integer.MIN_VALUE ? -1 : res;
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/leetcode/algo/u/UglyNumber.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.u;
2 |
3 | public class UglyNumber {
4 | public static boolean isUgly(int num) {
5 | if (num <= 0)
6 | return false;
7 | while (num % 2 == 0) {
8 | num /= 2;
9 | }
10 | while (num % 3 == 0) {
11 | num /= 3;
12 | }
13 | while (num % 5 == 0) {
14 | num /= 5;
15 | }
16 | return num == 1;
17 | }
18 | public static void main(String[] args){
19 | System.out.println(isUgly(215960780));
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/leetcode/algo/u/UniqueNumberofOccurrences.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.u;
2 |
3 | import java.util.HashMap;
4 | import java.util.HashSet;
5 | import java.util.Map;
6 | import java.util.Set;
7 |
8 | public class UniqueNumberofOccurrences {
9 | public boolean uniqueOccurrences(int[] arr) {
10 |
11 | Map map = new HashMap<>();
12 | for (int i = 0; i < arr.length; i++) {
13 | map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
14 | }
15 |
16 | Set set = new HashSet<>();
17 | for (int key : map.keySet()) {
18 | if (set.contains(map.get(key)))
19 | return false;
20 | set.add(map.get(key));
21 | }
22 | return true;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/algo/u/UniquePaths.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.u;
2 | /* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
3 | * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right
4 | * corner of the grid (marked 'Finish' in the diagram below).
5 | * How many possible unique paths are there?
6 | */
7 | public class UniquePaths {
8 | // TLE
9 | public int uniquePaths(int m, int n) {
10 | if (m == 1 || n == 1)
11 | return 1;
12 | return uniquePaths(m - 1, n) + uniquePaths(m, n - 1);
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/leetcode/algo/u/UniquePaths2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.u;
2 | /* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
3 | * The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right
4 | * corner of the grid (marked 'Finish' in the diagram below).
5 | * How many possible unique paths are there?
6 | */
7 | //TLE
8 | public class UniquePaths2 {
9 | public int uniquePaths(int m, int n) {
10 | return backtrack(0, 0, m, n);
11 | }
12 | public int backtrack(int r, int c, int m, int n) {
13 | if (r == m - 1 && c == n - 1)
14 | return 1;
15 | if (r > m - 1 || c > n - 1)
16 | return 0;
17 | return backtrack(r + 1, c, m, n) + backtrack(r, c + 1, m, n);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/leetcode/algo/v/ValidAnagram.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.v;
2 |
3 | import java.util.Arrays;
4 |
5 | /* Given two strings s and t, write a function to determine if t is an anagram of s.
6 | * For example,
7 | * s = "anagram", t = "nagaram", return true.
8 | * s = "rat", t = "car", return false.
9 | * Note: You may assume the string contains only lowercase alphabets.
10 | */
11 | public class ValidAnagram {
12 | public boolean isAnagram(String s, String t) {
13 | if (s.length() != t.length())
14 | return false;
15 | char[] sarray = s.toCharArray();
16 | char[] tarray = t.toCharArray();
17 | Arrays.sort(sarray);
18 | Arrays.sort(tarray);
19 | for (int i = 0; i < sarray.length; i++) {
20 | if (sarray[i] != tarray[i])
21 | return false;
22 | }
23 | return true;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode/algo/v/ValidNumber3.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.v;
2 | /* Validate if a given string is numeric.
3 | * Some examples:
4 | * "0" => true
5 | * " 0.1 " => true
6 | * "abc" => false
7 | * "1 a" => false
8 | * "2e10" => true
9 | * Note: It is intended for the problem statement to be ambiguous.
10 | * You should gather all requirements up front before implementing one.
11 | */
12 | public class ValidNumber3 {
13 | public boolean isNumber(String s) {
14 | if (s.trim().isEmpty())
15 | return false;
16 | String regex = "[-+]?(\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)?";
17 | if (s.trim().matches(regex))
18 | return true;
19 | else
20 | return false;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/v/ValidPermutationsforDISequence.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.v;
2 |
3 | public class ValidPermutationsforDISequence {
4 | }
5 |
--------------------------------------------------------------------------------
/src/leetcode/algo/w/WiggleSort2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.w;
2 |
3 | import java.util.Arrays;
4 |
5 | /* Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
6 | * For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
7 | */
8 | /* Time O(nlogn)
9 | * Space O(1)
10 | */
11 | public class WiggleSort2 {
12 | public void wiggleSort(int[] nums) {
13 | // 先将数组排序
14 | Arrays.sort(nums);
15 | // 将数组中一对一对交换
16 | for (int i = 2; i < nums.length; i += 2) {
17 | int tmp = nums[i - 1];
18 | nums[i - 1] = nums[i];
19 | nums[i] = tmp;
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/leetcode/algo/w/WiggleSort4.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.w;
2 |
3 | /* Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....
4 | * For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4].
5 | */
6 | /* Time O(nlogn)
7 | * Space O(1)
8 | */
9 | public class WiggleSort4 {
10 | public void wiggleSort(int[] nums) {
11 | for (int i = 1; i < nums.length; i++) {
12 | if ((i % 2 == 1) == (nums[i - 1] > nums[i])) {
13 | swap(nums, i - 1, i);
14 | }
15 | }
16 | }
17 |
18 | private void swap(int[] nums, int i, int j) {
19 | int temp = nums[i];
20 | nums[i] = nums[j];
21 | nums[j] = temp;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/leetcode/algo/x/XofaKindinaDeckofCards2.java:
--------------------------------------------------------------------------------
1 | package leetcode.algo.x;
2 |
3 |
4 | import java.util.HashMap;
5 | import java.util.Map;
6 |
7 | public class XofaKindinaDeckofCards2 {
8 | public boolean hasGroupsSizeX(int[] deck) {
9 | Map map = new HashMap<>();
10 | for (int c : deck) {
11 | map.put(c, map.getOrDefault(c, 0) + 1);
12 | }
13 |
14 | int g = map.values().iterator().next();
15 | for (int value : map.values()) {
16 | g = gcd(g, value);
17 | }
18 | return g >= 2;
19 | }
20 |
21 | public int gcd(int x, int y) {
22 | return x == 0 ? y : gcd(y % x, x);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/leetcode/bash/TenthLine :
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gaohannk/Leetcode/e0e111835b0fae2e27d80ac9e012f5052c6bd1a2/src/leetcode/bash/TenthLine
--------------------------------------------------------------------------------
/src/leetcode/bash/TransposeFile:
--------------------------------------------------------------------------------
1 | awk '
2 | {
3 | for (i = 1; i <= NF; i++) {
4 | if(NR == 1) {
5 | s[i] = $i;
6 | } else {
7 | s[i] = s[i] " " $i;
8 | }
9 | }
10 | }
11 | END {
12 | for (i = 1; s[i] != ""; i++) {
13 | print s[i];
14 | }
15 | }' file.txt
--------------------------------------------------------------------------------
/src/leetcode/bash/ValidPhoneNumbers:
--------------------------------------------------------------------------------
1 | awk '
2 | {
3 | for (i = 1; i <= NF; i++) {
4 | if(NR == 1) {
5 | s[i] = $i;
6 | } else {
7 | s[i] = s[i] " " $i;
8 | }
9 | }
10 | }
11 | END {
12 | for (i = 1; s[i] != ""; i++) {
13 | print s[i];
14 | }
15 | }' file.txt
--------------------------------------------------------------------------------
/src/leetcode/bash/WordFrequency:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gaohannk/Leetcode/e0e111835b0fae2e27d80ac9e012f5052c6bd1a2/src/leetcode/bash/WordFrequency
--------------------------------------------------------------------------------
/src/leetcode/common/HtmlParser.java:
--------------------------------------------------------------------------------
1 | package leetcode.common;
2 |
3 | import java.util.List;
4 |
5 | public interface HtmlParser {
6 | public List getUrls(String url);
7 | }
8 |
--------------------------------------------------------------------------------
/src/leetcode/common/ImmutableListNode.java:
--------------------------------------------------------------------------------
1 | package leetcode.common;
2 |
3 | public interface ImmutableListNode {
4 | void printValue(); // print the value of this node.
5 | ImmutableListNode getNext(); // return the next node.
6 | }
7 |
--------------------------------------------------------------------------------
/src/leetcode/common/ListNode.java:
--------------------------------------------------------------------------------
1 | package leetcode.common;
2 |
3 | public class ListNode {
4 | public int val;
5 | public ListNode next;
6 |
7 | public ListNode(int x) {
8 | val = x;
9 | next = null;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/leetcode/common/Node.java:
--------------------------------------------------------------------------------
1 | package leetcode.common;
2 |
3 | public class Node {
4 | public int val;
5 | public Node left;
6 | public Node right;
7 | public Node next;
8 |
9 | public Node(int val) {
10 | this.val = val;
11 | }
12 |
13 | public Node(int _val,Node _left,Node _right,Node _next) {
14 | val = _val;
15 | left = _left;
16 | right = _right;
17 | next = _next;
18 | }
19 | };
20 |
--------------------------------------------------------------------------------
/src/leetcode/common/TreeLinkNode.java:
--------------------------------------------------------------------------------
1 | package leetcode.common;
2 |
3 | public class TreeLinkNode {
4 | public int val;
5 | public TreeLinkNode left, right, next;
6 |
7 | TreeLinkNode(int x) {
8 | val = x;
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/leetcode/common/TreeNode.java:
--------------------------------------------------------------------------------
1 | package leetcode.common;
2 |
3 | public class TreeNode {
4 | public int val;
5 | public TreeNode left;
6 | public TreeNode right;
7 |
8 | public TreeNode(int x) {
9 | val = x;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/leetcode/common/TrieNode.java:
--------------------------------------------------------------------------------
1 | package leetcode.common;
2 |
3 | import java.util.HashMap;
4 |
5 | public class TrieNode {
6 | char c;
7 | HashMap children = new HashMap();
8 | int end;
9 |
10 | public TrieNode(char c) {
11 | this.c = c;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/leetcode/sql/FindCustomerReferee:
--------------------------------------------------------------------------------
1 | Given a table customer holding customers information and the referee.
2 |
3 | +------+------+-----------+
4 | | id | name | referee_id|
5 | +------+------+-----------+
6 | | 1 | Will | NULL |
7 | | 2 | Jane | NULL |
8 | | 3 | Alex | 2 |
9 | | 4 | Bill | NULL |
10 | | 5 | Zack | 1 |
11 | | 6 | Mark | 2 |
12 | +------+------+-----------+
13 | Write a query to return the list of customers NOT referred by the person with id '2'.
14 |
15 | For the sample data above, the result is:
16 |
17 | +------+
18 | | name |
19 | +------+
20 | | Will |
21 | | Jane |
22 | | Bill |
23 | | Zack |
24 | +------+
25 |
26 | SELECT name FROM customer WHERE referee_id <> 2 OR referee_id IS NULL;
27 |
--------------------------------------------------------------------------------
/src/leetcode/sql/ShortestDistanceinaLine:
--------------------------------------------------------------------------------
1 | Table point holds the x coordinate of some points on x-axis in a plane, which are all integers.
2 |
3 |
4 | Write a query to find the shortest distance between two points in these points.
5 |
6 |
7 | | x |
8 | |-----|
9 | | -1 |
10 | | 0 |
11 | | 2 |
12 |
13 |
14 | The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output is as below:
15 |
16 |
17 | | shortest|
18 | |---------|
19 | | 1 |
20 |
21 |
22 | SELECT MIN(ABS(p1.x - p2.x)) AS shortest
23 | FROM point p1
24 | JOIN point p2
25 | ON p1.x != p2.x;
--------------------------------------------------------------------------------