【LeetCode】马三来刷题之Remove Duplicates from Sorted Array
恢復(fù)刷題第二天,題目鏈接: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
題目很簡單,給定一個(gè)排序好的數(shù)組,把相同的元素從原來的位置移除,并且返回一個(gè)不包含重復(fù)元素的長度即可。
同樣是用了兩種方法過的這道題,分別是unique和數(shù)組逐個(gè)比較的辦法。
方法一:使用unique()函數(shù):
int removeDuplicates(vector<int>& nums) {//unique()函數(shù)將重復(fù)的元素放到vector的尾部 然后返回指向第一個(gè)重復(fù)元素的迭代器//再用erase函數(shù)擦除從這個(gè)元素到最后元素的所有的元素nums.erase(unique(nums.begin(),nums.end()),nums.end());return nums.size(); } 方法二:數(shù)組元素逐個(gè)比較:
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; }
每天一道題,保持新鮮感,就這樣~
總結(jié)
以上是生活随笔為你收集整理的【LeetCode】马三来刷题之Remove Duplicates from Sorted Array的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 流程控制:分支结构
- 下一篇: 【游戏开发】小白学Lua(上)