LeetCode第26題算法
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.微信
Example 1:app
Given 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 returned length.
Example 2:this
Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
Clarification:spa
Confused why the returned value is an integer but your answer is an array?翻譯
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.code
Internally you can think of this:blog
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) { print(nums[i]); }
翻譯:排序
給定一個已排序的數組,刪除其中重複的部分,保證每一個數字只出現一次,返回一個新的數組長度。
不要申明額外的數組空間,必須保證算法複雜度爲O(1)
思路:
既然不能申明額外的數組,那隻能在原來的數組上作變更
變更前:[1,1,2,3,3]
變更後:[1,2,3,3,3]
前3個值[1,2,3]就是咱們所須要的
代碼:
class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 0) return 0; int j =0; for(int i = 0;i<nums.length;i++){ if(nums[j]!=nums[i]){ j++; nums[j] = nums[i]; } } return j+1; } }
原數組遍歷一遍後,將不重複的數字保存在數組的前面,j就是咱們須要的數據的最大下標,那麼j+1就是咱們須要的長度
歡迎關注個人微信公衆號:安卓圈