码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Duplicates from Sorted Array

时间:2015-02-03 22:34:48      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

解题思路:

这道题考的是in place操作,应该还是比较容易的,一次通过。因为原数组已经排序,取一个swapIndex记录如果遇到一个更大的数,需要甩到前面的位置。那么怎么叫一个更大的数?这里需要一个比较的对象record,注意,不能直接和前一个数字比较,因为可能是1,2,1,3,3。1是刚被甩过来的。i扫描到数组末尾的时候,等待的swapIndex就是新数组的长度了。

public class Solution {
    public int removeDuplicates(int[] A) {
        if(A.length == 0){
            return 0;
        }
        
        int swapIndex = 1;
        int record = A[0];
        
        for(int i = 1; i < A.length; i++){
            if(A[i] > record){
                record = A[i];
                int temp = A[swapIndex];
                A[swapIndex] = A[i];
                A[i] = temp;
                swapIndex++;
            }
        }
        return swapIndex;
    }
}

这里还可以更简单点,因为新数组不要求后面的元素是啥,也就是说,可以直接将前面的数组覆盖,不用swap,这样也不要record这个变量了。

public class Solution {
    public int removeDuplicates(int[] A) {
        if(A.length == 0){
            return 0;
        }
        
        int swapIndex = 1;
        // int record = A[0];
        
        for(int i = 1; i < A.length; i++){
            if(A[i] > A[i - 1]){
                // record = A[i];
                // int temp = A[swapIndex];
                A[swapIndex] = A[i];
                // A[i] = temp;
                swapIndex++;
            }
        }
        return swapIndex;
    }
}

 

Remove Duplicates from Sorted Array

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4271026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!