-
[0027移除元素]
class Solution { public int removeElement(int[] nums, int val) { int slowIndex = 0; int fastIndex = 0; int numsLength = nums.length; for(fastIndex = 0; fastIndex <= numsLength-1; fastIndex++){ if(nums[fastIndex] != val){ //nums[slowIndex++] = nums[fastIndex]; nums[slowIndex] = nums[fastIndex]; slowIndex ++; } } return slowIndex; } }
- fastIndex先探访原数组中的每一个元素是否为目标元素,若是则自增后继续探访下一个元素,若不是则由slowIndex取值并同FastIndex一起自增;
-
[0977有序数组的平方]
class Solution { public int[] sortedSquares(int[] nums) { int slowIndex = 0; int fastIndex = 0; int numsLength = nums.length; int [] newNums = new int[numsLength]; for (int i = 0; i < numsLength; i++){ if(nums[i] <= 0) fastIndex = i; newNums[i] = nums[i] * nums[i]; } newNums[0] = nums[fastIndex]*nums[fastIndex]; int a = fastIndex-1; int b = fastIndex+1; for(int i = 1; i < numsLength; i++){ if(a < 0 || b > numsLength) break; if(nums[a]*nums[a] < nums[b]*nums[b]){ newNums[i] = nums[a]*nums[a]; a--; } else{ newNums[i] = nums[b]*nums[b]; b++; } } return newNums; } }
- 饶了那么多,就是想避开一次for循环赋值和一边排序(可选快排),但双指针还是没用对,不该先定最小的元素值,它在数组中间啊,怎么能有两端点值好找呢,不好找也罢,关键是两个移动的指针就没那么容易了,因为向两边移动会停止、会越界。
class Solution { public int[] sortedSquares(int[] nums) { int numsLength = nums.length; int i = 0; int j = numsLength-1; int [] newNums = new int [numsLength]; for (int k = 0; k <= nums.length-1; k++){ if (nums[i] * nums[i] >= nums[j] * nums[j]){ newNums[numsLength - k] = nums[i]; i++; } else{ newNums[numsLength - k] = nums[j]; j--; } } return newNums; } }
- 看懂思想了,但还是运行不成功,因为指针变量太绕了。。。
class Solution { public int[] sortedSquares(int[] nums) { int numsLength = nums.length; int i = 0; int j = numsLength - 1; int k = numsLength - 1; int [] newNums = new int [numsLength]; while(i <= j){ if (nums[i] * nums[i] >= nums[j] * nums[j]){ newNums[k--] = nums[i] * nums[i]; i++; } else{ newNums[k--] = nums[j] * nums[j]; j--; } } return newNums; } }
- 可以说是照抄了一遍。。。不得不说,相比于for循环,while不太会灵活运用。
-
[0209长度最小的子数组]
class Solution { public int minSubArrayLen(int target, int[] nums) { int numsLength = nums.length; for (int k = 0; k <= numsLength-1; k++){ int sum = 0; int i = 0; int j = i + k; while (j <= numsLength-1){ for(int temp = i; temp <= j; temp++){ sum = sum + nums[temp]; } if (sum >= target) return k+1; i++; j++; } } return 0; } }
- 确实看到提示说是用滑动窗口代替两个for循环,但调节滑动窗口的起始位置这部分精髓代码比较蒙''''''''''
明天继续:)
- 确实看到提示说是用滑动窗口代替两个for循环,但调节滑动窗口的起始位置这部分精髓代码比较蒙''''''''''