《leetcode》remove-duplicates-from-sorted-array-ii

来源:互联网 发布:国际航协2015数据 编辑:程序博客网 时间:2024/06/15 15:48

题目描述

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].

解析:借助hash的思想做该题目。

import java.util.*;public class Solution {    public int removeDuplicates(int[] A) {        List<Integer> list = new ArrayList<Integer>();        Map<Integer,Integer>  hash = new HashMap<>();        for(int i:A){            Integer value=hash.get(i);            if(value==null){//第一次出现该数字                hash.put(i,1);                list.add(i);            }else {                if(value<2){//该数字出现的次数少于2                    list.add(i);                    value++;                    hash.put(i,value);                }            }        }        for(int i=0;i<list.size();i++){            A[i]=list.get(i);        }        return list.size();    }}