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

Remove Duplicates from Sorted Array II

时间:2015-02-04 20:15:06      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

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

解题思路:

与Remove Duplicates from Sorted Array相比,这道题稍微复杂点。因为要求一个数字最多可以出现两次,很容易想到在上题的基础上,加入一个变量计数。i作为遍历游标,遇到比record大的数字时,操作不变,同时将count重置为1。区别就是,遇到和record相等的数字,原来是不需要操作的,这里首先count必须++。其次,如果在++前,count<2,那么还需要把当前数字和swapIndex的数字交换位置,同时swapIndex++。这种情况下的swap开始忘记了,导致程序一直出错。

同样,不swap,直接A[swapIndex] = A[i],也是可以的。

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

 

Remove Duplicates from Sorted Array II

标签:

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

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