日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】马三来刷题之Remove Duplicates from Sorted Array

發(fā)布時(shí)間:2023/12/16 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【LeetCode】马三来刷题之Remove Duplicates from Sorted Array 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

恢復(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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。