数组中重复的数字

数组中重复的数字

题目链接

https://www.nowcoder.com/practice/6fe361ede7e54db1b84adc81d09d8524?tpId=13&tqId=11203&tab=answerKey&from=cyc_github

题目描述

在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。

package com.huang.datastructure;

import com.sun.deploy.util.StringUtils;

/**
 * @Author hxc
 * @Date 2022/1/4
 */
public class ArraysDemo {
    /**
     * 在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,
     * 但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
     *
     * ```html
     * Input:
     * {2, 3, 1, 0, 2, 5}
     *
     * Output:
     * 2
     * ```
     */
    public static void main(String[] args) {

        int[] arr = { 3, 1 , 1, 5 , 0, 2, 5, 5};
        //int i = arrayDest(arr);
        //System.out.println(i);

        int duplicate = duplicate(arr);
        System.out.println(duplicate);
    }

    //第一种解法
    public static int arrayDest(int[] arr) {
        //时间复杂度为O(MN)
        for (int i = 0;i<arr.length;i++) {
            int temp = arr[i];
            for (int j = 1 + i;j<arr.length;j++) {
                if(temp == arr[j]){
                    return temp;
                }
            }
        }
        return -1;
    }

	//第二种解法
    public static int duplicate(int[] nums) {
        //时间复杂度为O(N)
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] != i) {
                if (nums[i] == nums[nums[i]]) {
                    return  nums[i];
                }
                swap(nums, i, nums[i]);
            }
            swap(nums, i, nums[i]);
        }
        return -1;
    }

    private static void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
}
posted @   China熊孩子  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理

阅读目录(Content)

此页目录为空

点击右上角即可分享
微信分享提示