天天演算法 | Easy | 3. 去除有序數組中的重複元素

每天來一道,面試不卡殼。這是碼蜂社天天演算法陪你成長的第 3 天。


此題可在 leetcode 上 oj,鏈接:Remove Duplicates from Sorted Array

題目描述:

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 doesnt matter what you leave beyond the new length.

題目翻譯

給定一個已經排序好的數組,刪除重複的元素,得到一個每個元素只顯示一次的新數組,返回值為新數組的長度。 不要為另一個數組分配額外的空間,您必須使用常量內存來執行此操作。

例如,

給定輸入數組nums = [1,1,2], 您的函數應返回長度2,同時數組被更新為nums = [1,2]。

解題方案

標籤: Array

思路:

  • 當數組長度為0或者1時,直接訪問長度值即可,不存在重複元素。
  • 如果超過1,則對數組進行遍歷,使用index變數指向數組更新位置,i變數指向數組遍歷位置。
  • 如果nums[inde] != nums[i]成立,則先移動index,然後更新,否則不更新。
  • 返回值index少加了一次,故而為index+1

代碼:

class Solution {n public int removeDuplicates(int[] nums) {n if(nums.length == 0 || nums.length ==1)n return nums.length;n int index = 0; n for(int i=1;i<nums.length;i++){n if(nums[index]!=nums[i]){n index++;n nums[index] = nums[i];n }n }n return index+1;n }n}n


歡迎加入碼蜂社演算法交流群:476497599

掃描下方二維碼或搜索「碼蜂社」公眾號,不怕錯過好文章:

推薦閱讀:

追MM的各種演算法
九章演算法 | Facebook面試題 : 迷你解析器
實際工作中怎麼驗證程序寫對了?
專欄總目錄
想讓視頻網站乖乖幫你推內容?看看這位小哥是如何跟YouTube鬥法的

TAG:前端开发 | Web开发 | 算法 |