数组
主要是双指针
二分查找法
LeetCode 704
遵循原则:左闭右开(推荐) | 左闭右闭 | 左开 可以但不推荐
[left, right]	|	[left, right)	| (left, right] 	| 	(left, right)
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 
 | left = 0right = num.size - 1
 
 
 
 
 while(left __ right){
 middle = (left+right)/2
 
 
 if(nums[middle] > target){
 
 right = middle - 1
 right = middle
 }
 
 
 else if(nums[middle] < target){
 left = middle + 1
 }
 
 else
 return middle
 
 }
 return -1
 
 | 
移除元素
LeetCode 27
提要:删除数组中的指定元素,实际上是覆盖操作!
双指针思路,一个快指针,一个慢指针
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | 
 
 
 slow = 0
 fast = 0
 
 for(let i = 0; i < arr.length; i++){
 if(arr[slow] != target){
 arr[slow++] = arr[fast]
 }
 
 
 }
 
 return slow;
 
 | 
有序数组的平方
LeetCode 977
思路一:数组每个数都先平方,然后在排序,时间复杂度 O(nlogn) ,空间复杂度 O(1)
思路二:双指针,因为最大平方后最大的元素位于数组两端,时间复杂度 O(n),空间复杂度 O(n)
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | 
 
 
 i = 0
 j = nums.length - 1
 result = Array(nums.length)		k = nums.length - 1
 
 
 while(i<=j){
 if(nums[i]² < nums[j]²){
 result[k--] = nums[j--]²
 }
 else{
 result[k--] = nums[i++]²
 }
 }
 return result;
 
 | 
长度最小的子数组(滑动窗口)
LeetCode 209
双指针:滑动窗口
简单来说就是:
	小了 前面的往前移动 扩大窗口;
	大了 后面的往前移动 缩小窗口
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | 
 
 
 
 i = 0
 k = 0
 result = Max
 count = 0
 for(i = 0; i < nums.length; i++){
 count += nums[i]
 while(count >= target){
 result = Min(result, i - k + 1)
 
 count = count - nums[k++]
 }
 }
 return resule;
 
 | 
螺旋矩阵
LeetCode 59
遵循原则:左闭右开
| 12
 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
 
 | 
 
 
 坐标:(x,y)
 count = 1
 
 startX = 0
 startY = 0
 offset = 1
 
 k = n / 2
 while(k--){
 
 for(x = startX, y = startY; y < n - offset; y++){
 nums[x][y] = count++
 }
 
 for(; x < n - offset; x++){
 nums[x][y] = count++
 }
 
 for(; y > startY; y--){
 nums[x][y] = count++
 }
 
 for(; x > startX; x--){
 nums[x][y] = count++
 }
 
 
 startX++;		startY++;		offset++;
 
 
 }
 
 
 
 if(n % 2){
 nums[x][y] = count
 }
 return nums
 
 |