数组去重

2019-04-24  本文已影响0人  霍运浩

题目描述

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A =[1,1,2],

Your function should return length =2, and A is now[1,2].

解题思路

构造一个List集合,每次add元素先看list集合存在该数字嘛,存在则不add,否则则add。

代码实现

import java.util.*;

public class Main {
    public int removeDuplicates(int[] A) {
       if(A==null || A.length<=1){
           return 0;
       }
       List<Integer> list=new ArrayList<Integer>();
       for(int i=0;i<A.length;i++){
            if(list.contains(A[i])){
                continue;
            }
            list.add(A[i]);
       }
        return list.size();
    }
}
上一篇下一篇

猜你喜欢

热点阅读