Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
What if duplicates are allowed at most twice?
For example,
Given sorted array nums =[1,1,1,2,2,3] ,
Given sorted array nums =
Your function should return length = 5 , with the first five elements of nums being 1 , 1 , 2 , 2 and 3 . It doesn't matter what you leave beyond the new length.
<Solution>這題是 Remove Duplicates from Sorted Array 的衍生題
這次多了可以指定每個數字能重覆幾次
思考方式還是一樣,只是多了一個 counter 來滿足題目需求
code 如下
c++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int removeDuplicates(vector<int>& nums) { | |
int newLen = !nums.empty(); | |
int cnt; | |
for(int i = 0; i < nums.size(); i++) { | |
if(i == 0) { | |
//> first element should be in the array | |
cnt = 1; | |
} | |
else if(nums[i] == nums[newLen - 1] && cnt < 2) { | |
//> found duplicates but less than 2 times | |
nums[newLen++] = nums[i]; | |
++cnt; | |
} | |
else if(nums[i] > nums[newLen - 1]) { | |
//> non-duplicates | |
nums[newLen++] = nums[i]; | |
cnt = 1; | |
} | |
} | |
return newLen; | |
} | |
}; |
kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun removeDuplicates(nums: IntArray): Int { | |
var index = 1 | |
var count = 1 | |
for (i in 1 until nums.size) { | |
if (nums[i] > nums[index-1]) { | |
nums[index++] = nums[i] | |
count = 1 | |
} else if (nums[i] == nums[index-1] && count == 1) { | |
nums[index++] = nums[i] | |
count = 2 | |
} | |
} | |
return index | |
} | |
} |
沒有留言:
張貼留言