一、理论基础
- 数组是存放在连续内存空间上的相同类型数据的集合。
- 删除或者增添元素的时候,就难免要移动其他元素的地址。
- 数组的元素是不能删的,只能覆盖。
二、二分查找
-
思路
- 二分过程,保证区间一致性
-
题目
- 给定一个
n
个元素有序的(升序)整型数组nums
和一个目标值target
,写一个函数搜索nums
中的target
,如果目标值存在返回下标,否则返回-1
。
- 给定一个
-
代码
class Solution { public int search(int[] nums, int target) { if (nums[nums.length - 1] < target || nums[0] > target) { return -1; } int left = 0; int right = nums.length; while (right > left) { int mid = left + ((right - left) >> 1); if (nums[mid] > target) { right = mid; } else if (nums[mid] < target) { left = mid + 1; } else { return mid; } } return nums[left] == target ? left : -1; } }
三、移除元素
-
思路
-
题目
-
代码
class Solution { public int removeElement(int[] nums, int val) { int res = nums.length; int slow = 0; for (int fast = 0; fast < nums.length; fast++) { if (nums[fast] == val) { res--; continue; } nums[slow++] = nums[fast]; } return res; } }
四、有序数组的平方
-
思路
- 双指针
-
题目
- 给你一个按 非递减顺序 排序的整数数组
nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
- 给你一个按 非递减顺序 排序的整数数组
-
代码
class Solution { public int[] sortedSquares(int[] nums) { int[] res = new int[nums.length]; int left = 0; int right = nums.length - 1; int index = res.length - 1; while (right >= left) { int temp = 0; if (Math.abs(nums[left]) < Math.abs(nums[right])) { temp = nums[right--]; } else { temp = nums[left++]; } res[index--] = (int) Math.pow(temp, 2); } return res; } }
五、长度最小的子数组
-
思路
- 滑动窗口
-
题目
-
给定一个含有
n
个正整数的数组和一个正整数target
。找出该数组中满足其总和大于等于target
的长度最小的 连续子数组[numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度。如果不存在符合条件的子数组,返回0
。
-
-
代码
class Solution { public int minSubArrayLen(int target, int[] nums) { int res = nums.length + 1; int slow = 0; int sum = 0; for (int fast = 0; fast < nums.length; fast++) { sum += nums[fast]; while (sum >= target) { res = Math.min(res, fast - slow + 1); sum -= nums[slow++]; } } return res == nums.length + 1 ? 0 : res; } }
六、螺旋矩阵II
-
思路
- 代码模拟
-
题目
- 给你一个正整数
n
,生成一个包含1
到n2
所有元素,且元素按顺时针顺序螺旋排列的n x n
正方形矩阵matrix
。
- 给你一个正整数
-
代码
class Solution { public int[][] generateMatrix(int n) { int[][] res = new int[n][n]; int circle = 1; int num = 1; while (circle < n) { int x = circle - 1; int y = circle - 1; for (; x < n - circle; x++) { res[y][x] = num++; } for (; y < n - circle; y++) { res[y][x] = num++; } for (; x >= circle; x--) { res[y][x] = num++; } for (; y >= circle; y--) { res[y][x] = num++; } circle++; } if (n % 2 != 0) { res[n / 2][n / 2] = num; } return res; } }
七、总结
- 二分:循环不变量原则,在循环中区间的定义不变;