LeetCode - Algorithms - 326. Power of Three

Java

1 Integer.Max_Value

1
2
3
4
5
class Solution {
public boolean isPowerOfThree(int n) {
return n>0 && 1162261467%n==0?true:false;
}
}

Submission Detail

  • Runtime: 12 ms, faster than 99.94% of Java online submissions for Power of Three.
  • Memory Usage: 38.1 MB, less than 0.99% of Java online submissions for Power of Three.
  • 21038 / 21038 test cases passed.

2 Logarithm

1
2
3
4
5
6
7
class Solution {
public boolean isPowerOfThree(int n) {
if (n<=0) return false;
double power = Math.log10(n)/Math.log10(3);
return power==Math.ceil(power)?true:false;
}
}

Submission Detail

  • Runtime: 15 ms, faster than 52.50% of Java online submissions for Power of Three.
  • Memory Usage: 37.3 MB, less than 0.99% of Java online submissions for Power of Three.
  • 21038 / 21038 test cases passed.

LeetCode - Algorithms - 28. Implement strStr()

Java

1 KMP algorithm

北京大学信息科学与技术学院《数据结构与算法》 之 KMP模式匹配算法 ©版权所有
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public int[] nextVector(String P) {
int[] arr = new int[P.length()];
arr[0] = 0;
int k = 0;
for (int i = 1; i < P.length(); i++) {
k = arr[i - 1];

while (k > 0 && P.charAt(i) != P.charAt(k)) {
k = arr[k - 1];
}

if (P.charAt(i) == P.charAt(k))
arr[i] = k + 1;
else
arr[i] = 0;
}
return arr;
}

public int findPat_KMP(String S, String P, int[] N, int startIndex) {
int lastIndex = S.length() - P.length();
if (lastIndex < startIndex)
return -1;
int i = startIndex, j = 0;
for (; i < S.length(); i++) {
while (P.charAt(j) != S.charAt(i) && j > 0)
j = N[j - 1];
if (S.charAt(i) == P.charAt(j))
j++;
if (j == P.length())
return i - j + 1;
}
return -1;
}

public int strStr(String haystack, String needle) {
if (needle.isEmpty()) return 0;
int[] arr = nextVector(needle);
if (needle.isEmpty()) return 0;
return findPat_KMP(haystack,needle,arr,0);
}
}

Submission Detail

  • 74 / 74 test cases passed.
  • Runtime: 9 ms, faster than 26.57% of Java online submissions for Implement strStr().
  • Memory Usage: 38.5 MB, less than 0.98% of Java online submissions for Implement strStr().

2 JDK String indexOf

1
2
3
4
5
6
class Solution {
public int strStr(String haystack, String needle) {
if (needle.isEmpty()) return 0;
return haystack.indexOf(needle);
}
}

Submission Detail

  • 74 / 74 test cases passed.
  • Runtime: 3 ms, faster than 99.58% of Java online submissions for Implement strStr().
  • Memory Usage: 38.1 MB, less than 0.98% of Java online submissions for Implement strStr().

LeetCode - Algorithms - 26. Remove Duplicates from Sorted Array

Java

The size of a Java array is fixed when you allocate it, and cannot be changed.

You’ve to provide a fixed size for that Array, You can neither EXPAND or SHRINK that array.

1

26.[圖解]Remove Duplicates from Sorted Array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length<2) return nums.length;
int x=0,y=1;
while (y<nums.length) {
if (nums[x]==nums[y]) {
y+=1;
}
else {
x+=1;
nums[x]=nums[y];
y+=1;
}
}
return x+1;
}
}

Submission Detail

  • 161 / 161 test cases passed.
  • Runtime: 6 ms
  • Memory Usage: 39.8 MB
  • Your runtime beats 97.51 % of java submissions.

2

5 lines Java solution

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length==0) return 0;
int j=0;
for(int i=0;i<nums.length;i++) {
if (nums[i]!=nums[j])
nums[++j]=nums[i];
}
return ++j;
}
}

Submission Detail

  • 161 / 161 test cases passed.
  • Runtime: 7 ms
  • Memory Usage: 42 MB
  • Your runtime beats 61.11 % of java submissions.

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
if (nums.length < 2) return nums.length;
for (var i = 0; i < nums.length; i++) {
while (nums[i] === nums[i-1])
nums.splice(i, 1);
}
return nums.length;
};

Submission Detail

  • 161 / 161 test cases passed.
  • Runtime: 84 ms, faster than 42.35% of JavaScript online submissions for Remove Duplicates from Sorted Array.
  • Memory Usage: 37.7 MB, less than 22.92% of JavaScript online submissions for Remove Duplicates from Sorted Array.

Resources

LeetCode - Algorithms - 13. Roman to Integer

Java

JAVA—————-Easy Version To Understand!!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int romanToInt(String s) {
if (s==null || s.isEmpty()) return -1;
Map<Character, Integer> map = new HashMap<Character, Integer>();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
char[] arr = s.toCharArray();
int len = arr.length;
int sum = map.get(arr[len-1]);
for(int i=0;i<len-1;i++) {
if (map.get(arr[i])>=map.get(arr[i+1])) {
sum += map.get(arr[i]);
}
else {
sum -= map.get(arr[i]);
}
}
return sum;
}
}

Submission Detail

  • 3999 / 3999 test cases passed.
  • Runtime: 91 ms
  • Your runtime beats 20.92 % of java submissions.

LeetCode - Algorithms - 21. Merge Two Sorted Lists

I am confused with pointer and linked list since I tounched computer as freshman in university.

just verify solution of other guys.

Java

Iterative

© LeetCode – Merge Two Sorted Lists (Java)

The key to solve the problem is defining a fake head. Then compare the first elements from each list. Add the smaller one to the merged list. Finally, when one of them is empty, simply append it to the merged list, since it is already sorted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode p = head;

ListNode p1 = l1;
ListNode p2 = l2;
while (p1 != null && p2 != null) {
if (p1.val < p2.val) {
p.next = p1;
p1 = p1.next;
} else {
p.next = p2;
p2 = p2.next;
}
p = p.next;
}

if (p1 != null) {
p.next = p1;
}

if (p2 != null) {
p.next = p2;
}

return head.next;
}
}

Submission Detail

  • 208 / 208 test cases passed.
  • Runtime: 1 ms, faster than 20.84% of Java online submissions for Merge Two Sorted Lists.
  • Memory Usage: 40.2 MB, less than 12.09% of Java online submissions for Merge Two Sorted Lists.

Recursive

Java, 1 ms, 4 lines codes, using recursion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1==null) return l2;
if (l2==null) return l1;
if (l1.val<l2.val) {
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}
else {
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
}

Submission Detail

  • 208 / 208 test cases passed.
  • Runtime: 13 ms
  • Your runtime beats 34.74 % of java submissions.

LeetCode - Algorithms - 393. UTF-8 Validation

Just verify code of others.

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public boolean validUtf8(int[] data) {
int count=0;
for(int k : data) {
if (count==0) {
if ((k>>5)==0b110) count=1;
else if ((k>>4)==0b1110) count=2;
else if ((k>>3)==0b11110) count=3;
else if ((k>>7)==1) return false;
}
else {
if ((k>>6)!=0b10) return false;
count--;
}
}
return count==0;
}
}

binary (introduced in Java SE 7) 0b11110101 (0b followed by a binary number)

Submission Detail

  • 49 / 49 test cases passed.
  • Runtime: 6 ms
  • Your runtime beats 27.65 % of java submissions.

ref

LeetCode - Algorithms - 384. Shuffle an Array

It seemed that Spotify only let you click big green SHUFFLE PLAY button if you are not premium user.

Java

1 - Fisher–Yates shuffle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Random;

class Solution {
private int[] shuffleArr;
private int[] originalArr;

public Solution(int[] nums) {
originalArr = nums.clone();
shuffleArr = nums.clone();
}

/** Resets the array to its original configuration and return it. */
public int[] reset() {
return originalArr;
}

/** Returns a random shuffling of the array. */
public int[] shuffle() {
Random random = new Random();
int temp = 0;
int randomPosition = 0;
final int N = shuffleArr.length;
for(int i=shuffleArr.length-1;i>0;i--) {
randomPosition = random.nextInt(N);
temp = shuffleArr[i];
shuffleArr[i] = shuffleArr[randomPosition];
shuffleArr[randomPosition] = temp;
}
return shuffleArr;
}
}

Submission Detail

  • 10 / 10 test cases passed.
  • Runtime: 210 ms
  • Your runtime beats 38.29 % of java submissions.

2 the Knuth (or Fisher-Yates) shuffling algorithm

© Robert Sedgewick and Kevin Wayne

Proposition. [Fisher-Yates 1938] Knuth shuffling algorithm produces a uniformly random permutation of the input array in linear time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
private int[] shuffleArr;
private int[] originalArr;

public Solution(int[] nums) {
originalArr = nums.clone();
shuffleArr = nums.clone();
}

/** Resets the array to its original configuration and return it. */
public int[] reset() {
return originalArr;
}

/** Returns a random shuffling of the array. */
public int[] shuffle() {
final int N = shuffleArr.length;
int swap;
for (int i = 0; i < N; i++) {
int r = (int) (Math.random() * (i + 1));
swap = shuffleArr[r];
shuffleArr[r] = shuffleArr[i];
shuffleArr[i] = swap;
}
return shuffleArr;
}
}

/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int[] param_1 = obj.reset();
* int[] param_2 = obj.shuffle();
*/

Submission Detail

  • 10 / 10 test cases passed.
  • Runtime: 76 ms, faster than 76.75% of Java online submissions for Shuffle an Array.
  • Memory Usage: 47.2 MB, less than 6.24% of Java online submissions for Shuffle an Array.

3 - Collections.shuffle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class Solution {
private Integer[] shuffleArr;
private int[] originalArr;

public Solution(int[] nums) {
shuffleArr = new Integer[nums.length];
for(int i=0;i<nums.length;i++)
shuffleArr[i] = nums[i];
originalArr = nums.clone();
}

/** Resets the array to its original configuration and return it. */
public int[] reset() {
return originalArr;
}

/** Returns a random shuffling of the array. */
public int[] shuffle() {
List<Integer> list = Arrays.asList(shuffleArr);
Collections.shuffle(list);
Integer[] a = new Integer[shuffleArr.length];
list.toArray(a);
int[] r = new int[a.length];
for(int i=0;i<a.length;i++)
r[i] = a[i];
return r;
}
}

Submission Detail

  • 10 / 10 test cases passed.
  • Runtime: 141 ms
  • Your runtime beats 96.48 % of java submissions.

ref

LeetCode - Algorithms - 706. Design HashMap

In Java collections framework, HashMap is the class I used most. Hash function is a hard problem.

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class MyHashMap {
static final int N = 1000000;
private int[] arr;

/** Initialize your data structure here. */
public MyHashMap() {
arr = new int[N];
Arrays.fill(arr, -1);
}

/** value will always be non-negative. */
public void put(int key, int value) {
arr[key]=value;
}

/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
public int get(int key) {
return arr[key];
}

/** Removes the mapping of the specified value key if this map contains a mapping for the key */
public void remove(int key) {
arr[key]=-1;
}
}

Submission Detail

  • 33 / 33 test cases passed.
  • Runtime: 150 ms
  • Your runtime beats 13.66 % of java submissions.

LeetCode - Algorithms - 53. Maximum Subarray

Tagged as easy, I feel it is not easy to solve. dynamic programming class problem. The solution is others, I only verify it.

Java

1 Kadane’s algorithm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int maxSubArray(int[] nums) {
int max = Integer.MIN_VALUE;
int count = 0;
for(int i=0;i<nums.length;i++) {
count += nums[i];
if (count>max)
max = count;
if (count<0)
count = 0;
}
return max;
}
}

Submission Detail

  • 202 / 202 test cases passed.
  • Runtime: 10 ms
  • Your runtime beats 40.59 % of java submissions.

2 DP

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int maxSubArray(int[] nums) {
int newSum = nums[0];
int max = nums[0];
for(int i=1;i<nums.length;i++) {
newSum = Math.max(newSum+nums[i], nums[i]);
max = Math.max(newSum, max);
}
return max;
}
}

Submission Detail

  • 202 / 202 test cases passed.
  • Runtime: 7 ms
  • Your runtime beats 89.29 % of java submissions.

ref

LeetCode - Algorithms - 69. Sqrt(x)

Java

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public int mySqrt(int x) {
if (x < 0)
return 0;
else if (x < 2)
return x;
else {
long smallCandidate = mySqrt(x >> 2) << 1;
long largeCandidate = smallCandidate + 1;
if (largeCandidate*largeCandidate > x)
return new Long(smallCandidate).intValue();
else
return new Long(largeCandidate).intValue();
}
}
}

Submission Detail

  • 1017 / 1017 test cases passed.
  • Runtime: 36 ms
  • Your runtime beats 17.73 % of java submissions.

2

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int mySqrt(int x) {
if (x==0 || x==1) return x;
long i=1, result=1;
while(result<=x) {
i++;
result = i*i;
}
return new Long(i-1).intValue();
}
}

Submission Detail

  • 1017 / 1017 test cases passed.
  • Runtime: 33 ms
  • Your runtime beats 24.03 % of java submissions.

3 O(logn)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public int mySqrt(int x) {
if (x == 0 || x == 1)
return x;

long start = 1, end = x, ans = 0;
while (start <= end) {
long mid = (start + end) / 2;

if (mid * mid == x)
return new Long(mid).intValue();

if (mid * mid < x) {
start = mid + 1;
ans = mid;
} else
end = mid - 1;
}
return new Long(ans).intValue();
}
}

Submission Detail

  • 1017 / 1017 test cases passed.
  • Runtime: 16 ms
  • Your runtime beats 95.09 % of java submissions.

ref