《leetcode》remove-duplicates-from-sorted-array-ii
生活随笔
收集整理的這篇文章主要介紹了
《leetcode》remove-duplicates-from-sorted-array-ii
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述
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){//第一次出現(xiàn)該數(shù)字hash.put(i,1);list.add(i);}else {if(value<2){//該數(shù)字出現(xiàn)的次數(shù)少于2list.add(i);value++;hash.put(i,value);}}}for(int i=0;i<list.size();i++){A[i]=list.get(i);}return list.size();} }總結(jié)
以上是生活随笔為你收集整理的《leetcode》remove-duplicates-from-sorted-array-ii的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《leetcode》valid-pare
- 下一篇: 字符串里解析vue表达式