Training camp day 1 | TUE | Sep 20
It's the first day to start concentrating on Leetcode Algorithm. I write my blogs using English in order to prepare for the interview and learn English better. I use Java to implement algorithms.
Today's Algorithm:
- Binary search
- Fast and slow pointer
ARRAY-数组
An array is a collection of itemrs stored at contiguous memory locations. Compared with other data structures, arrays have three characteristics:
- The arrays started from 0;
- The address of the array memory space is continuous;
- The elements of the array cannot be deleted and can only be overwritten.
Binary Search:
Leetcode 704. Binary Search
Given an array of integers
numswhich is sorted in ascending order, and an integertarget, write a function to searchtargetinnums. Iftargetexists, then return its index. Otherwise, return-1.You must write an algorithm with
O(log n)runtime complexity.
Thought:
- sorted in ascending order ,which means ordered array.
O(log n)runtime complexity
Try Binary Search after seeing these two conditions.
class Solution {
public int search(int[] nums, int target) {
int left = -1;
int right = nums.length;
while(left + 1 != right){
int middle = (left + right)/2;
if(nums[middle] == target){
return middle;
} else if(nums[middle] < target){
left = middle;
} else if(nums[middle] > target){
right = middle;
}
}
return -1;
}
}
Leetcode 35. Search Insert Position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with
O(log n)runtime complexity.
Thought:
- Sorted array
- O(log n)
A clever method:
class Solution {
public int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++){
if (nums[i] >= target){
return i;
}
}
return nums.length;
}
}
Fast and slow pointer
- Quick pointer: Look for elements of a new array, which is an array that does not contain target elements.
- Slow pointer: Point to the position of the updated new array subscript
Leetcode 27. Remove Element
class Solution {
public int removeElement(int[] nums, int val) {
/* int size = nums.length;
for (int i = 0; i < size; i++){
if(nums[i] == val){
for (int j = i + 1; j < size; j++){
nums[j - 1] = nums[j];
}
i--;
size--;
}
}
return size; */
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.length; fastIndex++){
if(val != nums[fastIndex]){
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
}