LeetCode-26: 删除排序数组中的重复项
題目描述:
給定一個(gè)排序數(shù)組,你需要在原地刪除重復(fù)出現(xiàn)的元素,使得每個(gè)元素只出現(xiàn)一次,返回移除后數(shù)組的新長度。
不要使用額外的數(shù)組空間,你必須在原地修改輸入數(shù)組并在使用 O(1) 額外空間的條件下完成。
示例?1:
給定數(shù)組 nums = [1,1,2],?
函數(shù)應(yīng)該返回新的長度 2, 并且原數(shù)組 nums 的前兩個(gè)元素被修改為 1, 2。?
你不需要考慮數(shù)組中超出新長度后面的元素。
示例?2:
給定 nums = [0,0,1,1,1,2,2,3,3,4],
函數(shù)應(yīng)該返回新的長度 5, 并且原數(shù)組 nums 的前五個(gè)元素被修改為 0, 1, 2, 3, 4。
你不需要考慮數(shù)組中超出新長度后面的元素。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
?
1. C++
class Solution {
public:
? ? int removeDuplicates(vector<int>& nums) {
? ? ? ? if (nums.empty()){ //數(shù)組為空,直接返回0
? ? ? ? ? ? return 0;
? ? ? ? }
? ? ? ??
? ? ? ? int index = 0;
? ? ? ? for(int i=1;i<nums.size();++i){
? ? ? ? ? ? if(nums[index] != nums[i]){ //前后兩個(gè)元素不相同,表示有新的元素
? ? ? ? ? ? ? ? nums[++index] = nums[i];?
? ? ? ? ? ? }
? ? ? ? }
? ? ? ??
? ? ? ? return index+1;
? ? }
};
?
2. C
int removeDuplicates(int* nums, int numsSize){
? ? if (numsSize == 0) {
? ? ? ? return 0;
? ? }
? ??
? ? unsigned int index = 0;
? ? for (unsigned int i = 1; i < numsSize; ++i) {
? ? ? ? if (nums[index] != nums[i]) {
? ? ? ? ? ? nums[++index] = nums[i];
? ? ? ? }
? ? }
? ??
? ? return index + 1;
}
?
?
?
?
總結(jié)
以上是生活随笔為你收集整理的LeetCode-26: 删除排序数组中的重复项的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓tinyalsa源码,可使用make
- 下一篇: LeetCode-80: 删除排序数组