数组中不重复的数字数量

内容纲要

编程题

输入12334,删除重复项个数,返回不重复的数量,不能申请额外的空间

答:

package com.example.meetaug.demo;

import java.util.Arrays;

public class Code01 {
    /*
    输入12334
    删除重复项个数
    返回不重复的数量
    不能申请额外的空间
     */

    // O(logn)
    public static int getUniqueCount2(int[] nums) {
        int length = nums.length;

        if (length == 0) return 0;

        Arrays.sort(nums); // O(logn)
        int uniqueCount = 1;

        for (int i = 1; i < length; i++) { // O(n)
            if (nums[i] != nums[i - 1]) {
                uniqueCount++;
            }
        }
        return uniqueCount;
    }

    // O(n^3/4)
    public static int getUniqueCount1(int[] nums) {
        int length = nums.length;
        int uniqueCount = nums.length;

        if (length == 0) return 0;

        System.out.println("初始数组:" + Arrays.toString(nums));

        for (int i = 0; i < length; i++) {
            for (int j = i + 1; j < length; j++) {
                if (nums[i] == nums[j]) {
                    for (int k = j; k < length - 1; k++) {
                        nums[k] = nums[k + 1];
                    }
                    uniqueCount--;
                    length--;
                    j--;
                }
            }
            System.out.println("第 " + (i + 1) + " 次循环后数组:" + Arrays.toString(nums));
        }

        System.out.println("去重后数字的个数:" + uniqueCount);
        return uniqueCount;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 3, 4};
        int result1 = getUniqueCount1(nums);
        int result2 = getUniqueCount2(nums);
        System.out.println(result1);
        System.out.println(result2);
    }
}

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注

close
arrow_upward