移除元素
移除元素(leetcode27)
var removeElement = function(nums, val) {
const n = nums.length;
let left = 0;
for (let right = 0; right < n; right++) {
if (nums[right] !== val) {
nums[left] = nums[right];
left++;
}
}
return left;
};
删除有序数组中的重复项(leetcode26)
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
const n = nums.length;
if (n === 0) {
return 0;
}
let fast = 1, slow = 1;
while (fast < n) {
if (nums[fast] !== nums[fast - 1]) {
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
};
移动0(leetcode283)
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let slowIndex = 0;
for (let fastIndex = 0; fastIndex < nums.length; fastIndex++) {
if (nums[fastIndex] !== 0) {
[nums[slowIndex], nums[fastIndex]] = [nums[fastIndex], nums[slowIndex]];
slowIndex++;
}
}
};
比较含退格的字符串(leetcode844)
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
var backspaceCompare = function(S,T) {
let i = S.length - 1,
j = T.length - 1,
skipS = 0,
skipT = 0;
//大循环
while(i >= 0 || j >= 0) {
// S 循环
while(i >= 0) {
if(S[i] === '#') {
skipS++;
i--;
} else if(skipS > 0) {
skipS--;
i--;
} else break;
}
// T 循环
while(j >= 0) {
if(T[j] === '#') {
skipT++;
j--;
} else if(skipT > 0) {
skipT--;
j--;
}else break;
}
if(S[i] !== T[j]) return false;
i--;
j--;
}
return true;
};
有序数组的平方(leetcode977)
/**
* @param {number[]} nums
* @return {number[]}
*/
var sortedSquares = function(nums) {
const n = nums.length;
const ans = Array(n);
let i = 0, j = n - 1;
for (let p = n - 1; p >= 0; p--) {
const x = nums[i] * nums[i];
const y = nums[j] * nums[j];
if (x > y) {
ans[p] = x;
i++;
} else {
ans[p] = y;
j--;
}
}
return ans;
};
标签:return,nums,--,元素,fastIndex,++,let,数组,移除
From: https://blog.csdn.net/2203_75300307/article/details/140137277