2016年2月13日 星期六

LEET code -- 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 doesn't matter what you leave beyond the new length.


我第一版本寫成會把重複出現的全部移除   沒有保留一個
原因出在第5行  因為slow會去找第一個出現重複的位置  如果沒有替他保留  會直接覆蓋
fast去找第一個跟slow不一樣的值

在18行可以直接slow++  因為一但有重複值出現 那之後一定都要順移



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
int removeDuplicates(int* nums, int numsSize) {
    if(numsSize<=0)return 0;
    int slow=0,fast=0;
    while(slow+1<numsSize && nums[slow]!=nums[slow+1])slow++;
    slow++;//save one duplicate
    if(slow >= numsSize-1)return slow;//no duplicate
    else{
        fast=slow+1;
        while(fast<numsSize && (nums[fast]==nums[slow] ))fast++;
    }
    //if(fast >= numsSize-1)return slow;
    while(fast<numsSize){
        int temp=nums[fast];
        nums[fast]=nums[slow];
        nums[slow]=temp;
        fast++;
        while(fast<numsSize && (nums[fast]==nums[slow]))fast++;
        slow++;
        printf("%d %d ",slow,fast);
    }
    return slow;
}

--------------
更好解

一個for就可以解決


1
2
3
4
5
6
7
8
int removeDuplicates(int* nums, int numsSize) {
    if(numsSize<=0)return 0;
    int slow=0;
    for(int i=1;i<numsSize;i++){
        if(nums[slow]!=nums[i])nums[++slow]=nums[i];
    }
    return slow+1;
}

沒有留言:

張貼留言