704. 二分查找
class Solution {
public int search(int[] nums, int target) {
if(nums==null || nums.length==0){
return -1;
}
return searchTarget(nums, 0, nums.length-1, target);
}
private int searchTarget(int[] nums, int left, int right, int target){
//left和right都指向同一个元素,但该元素不等于target,于是之后就走到这一步
if(left>right){
return -1;
}
int mid = (left+right)/2;
if(nums[mid]==target){
return mid;
}else if(target<nums[mid]){
return searchTarget(nums, left, mid-1, target);
}else{
return searchTarget(nums, mid+1, right, target);
}
}
}
27. 移除元素
class Solution {
public int removeElement(int[] nums, int val) {
if(nums==null || nums.length==0){
return 0;
}
int i=0;
for(int j=0; j<nums.length; j++){
if(nums[j]!=val){
nums[i++]=nums[j];
}
}
return i;
}
}
977. 有序数组的平方
class Solution {
public int[] sortedSquares(int[] nums) {
if(nums==null || nums.length==0){
return nums;
}
for(int i=0; i<nums.length; i++){
nums[i]=nums[i]*nums[i];
}
Arrays.sort(nums);
return nums;
}
}
209.长度最小的子数组
暴力解法,超时,测试用例通过率:18 / 21
class Solution {
public int minSubArrayLen(int target, int[] nums) {
if(nums==null || nums.length==0){
return 0;
}
//计算nums数组的前缀和
//此处preSum数组被初始化为全0数组
int[] preSum = new int[nums.length+1];
for(int i=0; i<nums.length; i++){
preSum[i+1] = preSum[i]+nums[i];
}
int minLength=nums.length+1;
int flag=0;//minLength是否被修改过
for(int i=0; i<preSum.length; i++){
for(int j=i+1; j<preSum.length; j++){
if(preSum[j]-preSum[i]>=target){
minLength=(j-i)<minLength?(j-i):minLength;
flag=1;
}
}
}
if(flag==1)
return minLength;
else//如果minLength未修改过,不能直接返回
return 0;
}
}
AC 解法:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
if(nums==null || nums.length==0){
return 0;
}
//计算nums数组的前缀和
//此处preSum数组被初始化为全0数组
int[] preSum = new int[nums.length+1];
for(int i=0; i<nums.length; i++){
preSum[i+1] = preSum[i]+nums[i];
}
int minLength=Integer.MAX_VALUE;
int i=0;//左指针
for(int j=1; j<preSum.length; j++){//右指针
int sum=preSum[j]-preSum[i];
while(sum>=target){
minLength=Math.min(minLength,j-i);
sum-=nums[i];
i++;
}
}
//如果minLength未修改过,不能直接返回
return minLength==Integer.MAX_VALUE?0:minLength;
}
}
59. 螺旋矩阵 II
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int startx=0, starty=0;//每一圈的起始位置的坐标
int offset=1;//每填充一条边时都要留下最后一个位置,让下一条边来填充
int num=1;//矩阵中要填的数字
//(n/2)是要转的圈数,n=偶数时转(n/2)圈就填满了,n=偶数时转(n/2)圈还剩中间一个位置未填
for(int loop=0; loop<n/2; loop++){
int i=startx, j=starty;
for(; j<n-offset; j++){
matrix[startx][j]=num++;
}
for(; i<n-offset; i++){
matrix[i][j]=num++;
}
for(; j>=offset; j--){
matrix[i][j]=num++;
}
for(; i>=offset; i--){
matrix[i][j]=num++;
}
startx++;
starty++;
offset++;
}
if(n%2==1){
matrix[n/2][n/2]=num;
}
return matrix;
}
}