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