数组
数组是存放在连续内存空间上的相同类型数据的集合。
- 数组下标都是从0开始的。
- 数组内存空间的地址是连续的
二分法
704. 二分查找
class Solution {
public int search(int[] nums, int target) {
if(target <nums[0] || target > nums[nums.length-1]) return -1;
int left = 0;
int right = nums.length-1;
while(left <= right){
int mobile = (right-left)/2+left;
if(nums[mobile] == target) return mobile;
else if(nums[mobile] > target) right = mobile-1;
else if(nums[mobile] < target) left = mobile+1;
}
return -1;
}
}
双指针法
27. 移除元素 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public int removeElement(int[] nums, int val) {
int slow = 0;
for(int fast = 0; fast<nums.length;fast++){
if(nums[fast] != val){
nums[slow] = nums[fast];
slow++;
}
}
return slow;
}
}
在数组和链表中是否常见
滑动窗口
209. 长度最小的子数组 - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int right = 0;
int left = 0;
int sum = 0;
int sublentgh = Integer.MAX_VALUE;
for(right = 0; right<nums.length;right++){
sum += nums[right];
while(sum>=target){
sublentgh = Math.min(sublentgh,right-left+1);
sum -= nums[left];
left++;
}
}
return sublentgh ==Integer.MAX_VALUE?0:sublentgh;
}
}
模拟法
59. 螺旋矩阵 II - 力扣(LeetCode) (leetcode-cn.com)
class Solution {
public int[][] generateMatrix(int n) {
//生成一个数组
int[][] nums = new int[n][n];
//定义循环次数
int loop = n/2;
//定义开始的位置
int startx = 0;
int starty = 0;
//定义偏移量
int offest = 1;
//定义填充的数字
int count = 1;
//定义中间的位置
int mid = n/2;
while(loop > 0){
int i = startx;
int j = starty;
//模拟从左到右
for(;j<starty+n-offest;++j){
nums[i][j] = count;
count++;
}
//从上到下
for(;i<startx+n-offest;++i){
nums[i][j] = count;
count++;
}
//从右到左
for(;j>starty;j--){
nums[i][j] = count;
count ++;
}
//从下到上
for(;i>starty;i--){
nums[i][j] = count;
count ++;
}
loop --;
startx = startx+1;
starty=starty+1;
offest += 2;
//如果是奇数需要单独赋值
}
if (n % 2 == 1) {
nums[mid][mid] = count;
}
return nums;
}
}