首页 > 其他 > 详细

Leetcode 80. Remove Duplicates from Sorted Array II

时间:2016-01-19 06:52:18      阅读:228      评论:0      收藏:0      [点我收藏+]

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

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

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn‘t matter what you leave beyond the new length.


解题思路:

Two pointers


Java code 

九章算法

public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int cur = 0;
        int i, j;
        for(i = 0; i< nums.length;) {
            int now = nums[i];
            for(j = i; j < nums.length; j++) {
                if(nums[j] != now){
                    break;
                }
                if(j - i < 2){
                    nums[cur++] = now;
                }
            }
            i = j;
        }
        return cur;
    }
}

Reference:

1. http://www.jiuzhang.com/solutions/remove-duplicates-from-sorted-array-ii/

 

Leetcode 80. Remove Duplicates from Sorted Array II

原文:http://www.cnblogs.com/anne-vista/p/5140974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!