LeetCode集錦(八) - 第26題 Remove Duplicates From Sorted Array

LeetCode集錦(八) - 第26題 Remove Duplicates From Sorted Array

問題

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: 


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: 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: 

 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. 

 Internally you can think of this: 


// 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:
給定nums = [1,1,2],
函數應該返回length = 2, nums的前兩個元素分別爲1和2。
在返回長度以外留下什麼並不重要。
示例2:
給定nums = [0,0,1,1,1,2,2,3,3,4],
函數應該返回length = 5, nums的前五個元素分別修改成0、一、二、3和4。
在返回長度以外設置什麼值並不重要。
澄清:
爲何返回的值是整數而您的答案是數組?
注意,輸入數組是經過引用傳入的,這意味着調用者也知道對輸入數組的修改。
你能夠這樣想:
// nums是經過引用傳入的。(即。,無須複印)
int len = removeduplicate (nums);
//函數中對nums的任何修改都會被調用者知道。
//使用函數返回的長度,它輸出第一個len元素。
for (int i = 0;i<len;i++){
print (num[i]);
}數組


解題思路

本題思路很簡單,要求咱們使用O(1)的空間,也就是咱們只能在當前數組上操做,由題目可知,數組是排序的,因此只要遍歷一次,把不重複的往前面放,那麼最前面的就是咱們須要的結果。bash

解題方法

  1. 按照咱們的思路來編輯,代碼以下app

    if (nums.length <= 1) {
            return nums.length;
        }
        int number = 0;
    
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[number]) {
                number++;
                nums[number] = nums[i];
            }
        }
    
        return number + 1;
    複製代碼

    時間複雜度: 該方案用了循環,循環層數爲1,即T(n)=O(n)函數

    空間複雜度: 該方案沒有使用額外的空間,因此空間複雜度是O(1);ui

總結

本題的大體解法如上所訴,本題只想到了一種方法,直接按照思路編寫this

相關文章
相關標籤/搜索