日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發布時間:2023/12/16 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。