Leet Code
Leet Code
Program Creek
Version 0.0
Contents
6 Word Ladder 20
9 Merge Intervals 27
10 Insert Interval 29
11 Two Sum 31
14 3Sum 34
15 4Sum 36
16 3Sum Closest 38
19 Valid Parentheses 42
20 Implement strStr() 43
2 | 181
Contents
24 Valid Palindrome 49
25 Spiral Matrix 52
26 Search a 2D Matrix 55
27 Rotate Image 56
28 Triangle 58
36 Palindrome Partitioning 73
41 Min Stack 79
42 Majority Element 80
43 Combination Sum 82
49 Largest Number 89
50 Combinations 90
52 Gas Station 93
53 Candy 95
54 Jump Game 96
55 Pascal’s Triangle 97
96 Permutations 169
97 Permutations II 171
You may have been using Java for a while. Do you think a simple Java array question
can be a challenge? Let’s use the following problem to test.
Problem: Rotate an array of n elements to the right by k steps. For example, with n
= 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
How many different ways do you know to solve this problem?
In a straightforward way, we can create a new array and then copy elements to the
new array. Then change the original array by using System.arraycopy().
public void rotate(int[] nums, int k) {
if(k > nums.length)
k=k%nums.length;
int j=0;
for(int i=k; i<nums.length; i++){
result[i] = nums[j];
j++;
}
7 | 181
1 Rotate Array in Java
Can we do this in O(1) space and in O(n) time? The following solution does.
Assuming we are given 1,2,3,4,5,6 and order 2. The basic idea is:
1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Rotate first part: 4,3,2,1,5,6
3. Rotate second part: 4,3,2,1,6,5
4. Rotate the whole array: 5,6,1,2,3,4
reverse(arr, 0, a-1);
reverse(arr, a, arr.length-1);
reverse(arr, 0, arr.length-1);