题目1:【二刷完成】
【需要注意的是,不要在原数组上改变元素数值,会引起数组絮乱】
代码1:
class Solution {
public int[] sortedSquares(int[] nums) {
/*双指针法*/
/*我感觉这是用到了三个指针,原来数组左右两个指针,新数组的最右边的一个指针 */
int[] newNums=new int[nums.length];
int left=0;
int right=nums.length-1;
int index=newNums.length-1;
while(left<=right){
int aa=nums[left]*nums[left];
int bb=nums[right]*nums[right];
if (aa >bb){
newNums[index--]=aa;
left++;
}else{
newNums[index--]=bb;
right--;
}
}
return newNums;
}
}
题目2:【二刷完成】
代码2:
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int sum=0;
int j=0;
int i=0;
int sublength;
int result=Integer.MAX_VALUE; //这儿必须比数组长度大,因为答案很可能就是数组长度
for (i=0; i<nums.length; i++){
sum += nums[i];
while(sum >= target){
sublength=i-j+1;
result= Math.min (result,sublength);
sum =sum -nums[j];
j++;
}
}
return result==Integer.MAX_VALUE ? 0 : result;
}
}
题目3:【二刷完成】
代码3:
class Solution {
public int[][] generateMatrix(int n) {
int[][] res=new int[n][n];
int startx=0;
int starty=0;
int offset=0;//旋转圈数
int count=1;
int i,j;
while(offset++ <n/2){
//从左到右
for (j=starty; j<n-offset; j++){
res[startx][j]=count++;
}
//从上到下
for (i=startx; i<n-offset; i++){
res[i][j]=count++;
}
//从右到左
for (; j>starty; j--){
res[i][j]=count++;
}
//从下到上
for ( ; i>startx; i--){
res[i][j]=count++;
}
startx++;
starty++;
}
if (n%2==1){
res[startx][starty]=count;
}
return res;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int[][] record = new int[n][n];
int count=1;//开始元素
int loop = 1;
int start = 0; //循环开始点
int i=0;
int j=0;
while(loop<= (n/2)){
for (j=start;j<n-loop;j++){
record[start][j]=count++;
}
for (i=start;i<n-loop;i++){
record[i][j]=count++;
}
for (;j>start;j--){
record[i][j]=count++;
}
for (;i>start;i--){
record[i][j]=count++;
}
start++;
loop++;
}
if (n%2==1){
record[loop-1][loop-1]=n*n;
}
return record;
}
}