LeetCode 80 Remove Duplicates from Sorted Array II(移除数组中出现两次以上的元素)

题目链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/#/description

给定一个已经排好序的数组,数组中元素存在重复,如果允许一个元素最多可出现两次,求出剔除重复元素(出现次数是两次以上的)后的数组的长度。

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.

要求:1. 返回数组的长度
         2. 确保上述长度内的数组为满足条件的元素,上述长度之外数组所保存的数字无关
 
很简单了,也就是判断每个数字出现了多少次就行了。不够两次的放到数组的新位置中,超过两次的不考虑。
 
给一个很笨的方法,这个方法实在是太low啦,不过为了突出很diao的那个方法有多么diao,还是贴出来啦。
不喜欢low low代码的请自动忽略,在此已将代码折叠。
 
package leetcode_100;

import java.util.HashMap;
import java.util.Map;
/***
 * 
 * @author pengfei_zheng
 * 移除数组中出现两次以上的元素
 */
public class Solution80{
    public int removeDuplicates(int[] nums) {
        int len = nums.length;
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("total",0);
        for(int i = 0 ;  i < len ; i ++){
            int temp = map.get("total");
            if(!map.containsKey(nums[i]+"")){
                map.put(nums[i]+"",1);
                nums[temp++]=nums[i];
                map.put("total",temp);
            }
            else if(map.containsKey(nums[i]+"")&&map.get(nums[i]+"")<2){
                map.put(nums[i]+"",2);
                nums[temp++]=nums[i];
                map.put("total",temp);
            }
        }
        return map.get("total");
    }
}
low low的代码

好的,还请忽略上述代码,请欣赏下面的代码:

public class Solution{
    public int removeDuplicates(int[] nums) {
        int i = 0;
        for (int n : nums)
            if (i < 2 || n > nums[i-2])
                nums[i++] = n;
        return i;
    }
}
这才是正确的姿势
原文地址:https://www.cnblogs.com/zpfbuaa/p/6635577.html