移除数组中的某个元素
题目来源:
leetcode 27.移除元素 https://leetcode.cn/problems/remove-element/
主要思想:
双指针
题解:
执行用时:0 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:39.9 MB, 在所有 Java 提交中击败了75.47% 的用户
通过测试用例:113 / 113
class Solution {
public int removeElement(int[] nums, int val) {
int first = 0;//放元素的位置
for(int second = 0; second < nums.length; second++){
if(nums[second] != val){
nums[first] = nums[second];
first++;
}
}
return first;
}
}
该题主要运用了快慢指针的思想,即两个指针可能不是一起走的,first指针指向的是非val元素存放的位置,而second指针去到后面搜索非val元素,找到非val元素就存入first指针存放的位置,然后first再指向下一个位置,直到second指针指向数组外,结束搜索,返回first
我们再看一道题!
有序数组的平方
题目来源:
leetcode977. 有序数组的平方 https://leetcode.cn/problems/squares-of-a-sorted-array/
主要思想:
双指针
题解:
执行用时:1 ms, 在所有 Java 提交中击败了100.00% 的用户
内存消耗:43.4 MB, 在所有 Java 提交中击败了21.95% 的用户
通过测试用例:137 / 137
class Solution {
public int[] sortedSquares(int[] nums) {
if(nums.length == 0){
return nums;
}
int[] nnums = new int[nums.length];
if(nums.length == 1){
nnums[0] = nums[0]*nums[0];
return nnums;
}
int head = 0;
int tail = nums.length-1;
int count = nums.length-1;
while(true){
if(nums[head]*nums[head]>=nums[tail]*nums[tail]){
nnums[count--] = nums[head]*nums[head];
head++;
}
else{
nnums[count--] = nums[tail]*nums[tail];
tail--;;
}
if(head>tail){
return nnums;
}
}
}
}
nums中,负数排在非负数后面,例如-4在1后面,可是-4的平方是16比1的平方1大,那么此时nums就不符合非单调递减的条件了,所以我们知道了,负数是这里需要考虑的东西(因为非负数那边本来就是平方后也符合规律的),而负数越小,平方越大,故我们需要从nums第一位和nums最后一位依次比较,大的放入新数组的最后一位,依次类推。