数组去重

Posted 黑小莲花

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组去重相关的知识,希望对你有一定的参考价值。

class Solution {
    public int removeDuplicates(int[] nums) {
       
        if(nums.length==0)
            return 0;
        int i=0;
        for(int j=1;j<nums.length;j++)
        {
            if(nums[j]!=nums[i])
            {
                i++;
                nums[i]=nums[j];
            }
        }
        return i+1;
    }
   
}

--------------------------------------------------------------------------

public class MainClass {
    public static int[] stringToIntegerArray(String input) {
        input = input.trim();
        input = input.substring(1, input.length() - 1);
        if (input.length() == 0) {
          return new int[0];
        }
   
        String[] parts = input.split(",");
        int[] output = new int[parts.length];
        for(int index = 0; index < parts.length; index++) {
            String part = parts[index].trim();
            output[index] = Integer.parseInt(part);
        }
        return output;
    }
   
    public static String integerArrayToString(int[] nums, int length) {
        if (length == 0) {
            return "[]";
        }
   
        String result = "";
        for(int index = 0; index < length; index++) {
            int number = nums[index];
            result += Integer.toString(number) + ", ";
        }
        return "[" + result.substring(0, result.length() - 2) + "]";
    }
   
    public static String integerArrayToString(int[] nums) {
        return integerArrayToString(nums, nums.length);
    }
   
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            int[] nums = stringToIntegerArray(line);
           
            int ret = new Solution().removeDuplicates(nums);
            String out = integerArrayToString(nums, ret);
           
            System.out.print(out);
        }
    }
}

以上是关于数组去重的主要内容,如果未能解决你的问题,请参考以下文章

js数组如何去重?

数组去重三种方法

对象数组去重

Set 数组去重

js中数组去重方法总结

ES6 数组内对象去重