Remove Duplicates from Sorted Array II (M)
題目
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,1,2,3,3],
Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
題意
給定一個有序陣列,要求將陣列中具有重復值的元素依次排在陣列前部,且同一個值對應的元素最多有兩個,回傳構成的新陣列的長度,
思路
在 26. Remove Duplicates from Sorted Array 的基礎上加上了條件:重復元素最多保留兩個,方法也比較簡單:設一個變數count記錄新陣列最后一個元素的重復次數,遍歷原陣列,每次都將當前元素和新陣列的最后一個元素進行比較,如果不同則直接移入新陣列,并將count重置為1;如果相同,判斷count的值,只有當重復次數count=1時才將當前元素移入新陣列,并使count加1,
代碼實作
Java
class Solution {
public int removeDuplicates(int[] nums) {
int p = 0;
int count = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[p] && count == 1) {
nums[++p] = nums[i];
count++;
} else if (nums[i] != nums[p]) {
nums[++p] = nums[i];
count = 1;
}
}
return p + 1;
}
}
JavaScript
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function (nums) {
let p = 0, q = 0
let cur = nums[0], cnt = 0
for (let num of nums) {
if (num === cur) {
cnt++
} else {
cur = num
cnt = 1
}
if (cnt <= 2) {
nums[p++] = nums[q]
}
q++
}
return p
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/233441.html
標籤:其他
上一篇:Python排序函式用法
