1 二分查找
class Solution {
public int search(int[] nums, int target) {
int n = nums.length;
int left = 0, right = n - 1, middle = 0;
while (left <= right) {//这里必须是<=,因为区间选择了左闭右闭
middle = left + ((right - left) >> 1);
if (nums[middle] > target) {
right = middle - 1;
} else if (nums[middle] < target) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
}
加减法+、-的优先级高于位移运算符>>、<<的优先级
因此(right - left) >> 1必须加括号。
【位移运算符】
>>1:右移一位,相当于除以2
<<1:左移一位,相当于乘2
2 移除元素
class Solution {
public int removeElement(int[] nums, int val) {
//解法:快慢指针,就像猴妈妈和小猴一样:
//猴妈妈走一步,只要不危险,小猴就跟着走;
//如果危险,小猴不动,猴妈妈再往下走,直到安全。
//等猴妈妈走完旧数组,小猴走的步数就是新数组的长度。
//[0,1,2,2,3,0,4,2],val=2
//
int slow = 0;
for (int fast = 0; fast < nums.length; fast ++) {//
if (nums[fast] != val) {//也就是 不危险的情况
nums[slow] = nums[fast];//猴妈妈让小猴走到自己站着的位置
slow ++;//小猴下一步所在的位置
}
}
return slow;
}
}
3 有序数组的平方
class Solution {
public int[] sortedSquares(int[] nums) {
int i = 0, j = nums.length - 1, k = nums.length - 1;
int[] res = new int[nums.length];
while (i <= j) {
if (nums[i] * nums[i] > nums[j] * nums[j]) {
res[k --] = nums[i] * nums[i];
i ++;
} else {
res[k --] = nums[j] * nums[j];
j --;
}
}
return res;
}
}
4 长度最小的子数组
暴力法:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int subLength = 0;
int sum = 0;
for (int left = 0; left < nums.length; left ++) {
sum = 0;
for (int right = left; right < nums.length; right ++) {
sum += nums[right];
if (sum >= target) {
subLength = right - left + 1;
res = res > subLength ? subLength : res;//若subLength更短则更新res
break;
}
}
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}
滑动窗口:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int res = Integer.MAX_VALUE;
int sum = 0;
int left = 0;
for (int right = 0; right < nums.length; right ++) {
sum += nums[right];
while (sum >= target) {
//subLength = right - left + 1;
res = Math.min(right - left + 1, res);
sum -= nums[left];
left ++;
}
}
return res == Integer.MAX_VALUE ? 0 : res;
}
}
5 螺旋矩阵Ⅱ
class Solution {
public int[][] generateMatrix(int n) {
int[][] nums = new int[n][n];
int loop = 0;
int count = 1;
int i = 0, j = 0;
int start = 0;
while (loop ++ < n / 2) {
for (j = start; j < n - loop; j ++) {
nums[start][j] = count ++;
}
for (i = start; i < n - loop; i ++) {
nums[i][j] = count ++;
}
for (; j > start; j --) {
nums[i][j] = count ++;
}
for (; i > start; i --) {
nums[i][j] = count ++;
}
start ++;
}
if (n % 2 == 1) {
nums[start][start] = count;
}
return nums;
}
}