【LeetCode】马三来刷题之Remove Duplicates from Sorted Array
恢復刷題第二天,題目鏈接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/?
26. Remove Duplicates from Sorted Array
?- Total Accepted:?157568
- Total Submissions:?454924
- Difficulty:?Easy
Given a sorted array, remove the duplicates in place such that each element appear only?once?and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array?nums?=?[1,1,2],
Your function should return length =?2, with the first two elements of?nums?being?1?and?2?respectively. It doesn't matter what you leave beyond the new length.
Subscribe?to see which companies asked this question
題目很簡單,給定一個排序好的數組,把相同的元素從原來的位置移除,并且返回一個不包含重復元素的長度即可。
同樣是用了兩種方法過的這道題,分別是unique和數組逐個比較的辦法。
方法一:使用unique()函數:
int removeDuplicates(vector<int>& nums) {//unique()函數將重復的元素放到vector的尾部 然后返回指向第一個重復元素的迭代器//再用erase函數擦除從這個元素到最后元素的所有的元素nums.erase(unique(nums.begin(),nums.end()),nums.end());return nums.size(); } 方法二:數組元素逐個比較:
int removeDuplicates(vector<int>& nums) {if (nums.empty()) 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; }
每天一道題,保持新鮮感,就這樣~
總結
以上是生活随笔為你收集整理的【LeetCode】马三来刷题之Remove Duplicates from Sorted Array的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 流程控制:分支结构
- 下一篇: 【游戏开发】小白学Lua(上)