注:大佬解答来自LeetCode官方题解
88.合并两个有序数组
1.题目
2.个人解答
var merge = function (nums1, m, nums2, n) {
//合并
for (let i = 0; i < n; i++) {
nums1[i + m] = nums2[i];
}
// 排序(冒泡排序)
for (let i = 0; i < m + n; i++) {
for (let j = 0; j < m + n - i - 1; j++) {
if (nums1[j] > nums1[j + 1]) {
[nums1[j], nums1[j + 1]] = [nums1[j + 1], nums1[j]];
}
}
}
};
3.大佬解答
var merge = function (nums1, m, nums2, n) {
nums1.splice(m, nums1.length - m, ...nums2);
nums1.sort((a, b) => a - b);
};
27.移除元素
1.题目
2.个人解答
var removeElement = function (nums, val) {
function remove(nums, i, val) {
if (nums[i] == val) {
nums.splice(i, 1);
remove(nums, i, val);
}
}
for (let i = 0; i < nums.length; i++) {
remove(nums, i, val);
}
};
3.大佬解答
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;
};
26.删除有序数组的重复项
1.题目
2.个人解答
var removeDuplicates = function (nums) {
const res = [];
for (let i = 0; i < nums.length; i++) {
const item = nums[i];
let isDuplicate = false;
for (let j = 0; j < res.length; j++) {
if (item === res[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
res.push(item);
}
}
nums.length = res.length;
for (let index = 0; index < nums.length; index++) {
nums[index] = res[index];
}
};
3.大佬解答
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;
};