删除排序数组中的重复数字 II

题目连接

http://www.lintcode.com/zh-cn/problem/remove-duplicates-from-sorted-array-ii/

题目大意

跟进“删除重复数字”:

如果可以允许出现两次重复将如何处理?

算法思想

因为数组中元素已经排好顺序的,直接遍历比较有几个是相同的,如果大于2个就直接把两个的存到一个数组中,最后返回数组的大小即可。

代码实现

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        int n = nums.length;
		int index = 0;
		for (int i = 0;i<n;i++) {
			if (i > 0 && i<n-1 && nums[i] == nums[i-1] && nums[i] == nums[i+1]) {
				continue;
			} else {
				nums[index++] = nums[i];
			}
		}
		return index;
    }
}

  

posted on 2017-10-18 16:00  airycode  阅读(279)  评论(0)    收藏  举报

导航