Array - Leetcode
Rotate
#189 Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
e.g arr = [1, 2, 3, 4, 5, 6, 7], k = 3.
- Reverse the whole array.
arr = [7, 6, 5, 4, 3, 2, 1]
- Rerverse two parts 0~k-1 and k~length-1.
1
2
3
4
5arr = [7, 6, 5, 4, 3, 2, 1]
| | |
0 k length-1
| | |
arr = [5, 6, 7, 1, 2, 3, 4]
Use 2 pointers to reverse.
My code
Sum
#167 Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
Think the story of Gauss.
The answer of 1 + 2 + 3 + … + 100 is (1 + 100) + (2 + 99) + … + (50 + 51)
We use two pointers - low and high1
2
3
4
5
6while(low < high){
current value = arr[low] + arr[high];
if(current value == target value) return;
else if(current value < target value) low++;
else(current value > target value) high--;
}