美文网首页
数组去重

数组去重

作者: 霍运浩 | 来源:发表于2019-04-24 22:17 被阅读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();
        }
    }
    

    相关文章

      网友评论

          本文标题:数组去重

          本文链接:https://www.haomeiwen.com/subject/fetogqtx.html