关于java:JZ050数组中重复的数字

数组中反复的数字

题目形容

在一个长度为n的数组里的所有数字都在0到n-1的范畴内。 数组中某些数字是反复的,但不晓得有几个数字是反复的。也不晓得每个数字反复几次。请找出数组中

  • 第一个反复的数字。 例如,如果输出长度为7的数组{2,3,1,0,2,5,3},那么对应的输入是第一个反复的数字2。
  • 返回形容:
  • 如果数组中有反复的数字,函数返回true,否则返回false。
  • 如果数组中有反复的数字,把反复的数字放到参数duplication[0]中。(ps:duplication曾经初始化,能够间接赋值应用。)

题目链接: 数组中反复的数字

代码

/**
 * 题目:数组中反复的数字
 * 题目形容
 * 在一个长度为n的数组里的所有数字都在0到n-1的范畴内。 数组中某些数字是反复的,但不晓得有几个数字是反复的。也不晓得每个数字反复几次。请找出数组中
 * 第一个反复的数字。 例如,如果输出长度为7的数组{2,3,1,0,2,5,3},那么对应的输入是第一个反复的数字2。
 * 返回形容:
 * 如果数组中有反复的数字,函数返回true,否则返回false。
 * 如果数组中有反复的数字,把反复的数字放到参数duplication[0]中。(ps:duplication曾经初始化,能够间接赋值应用。)
 * <p>
 * 题目链接
 * https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&&tqId=11203&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
 */
public class Jz50 {

    /**
     * 暴力破解
     *
     * @param numbers
     * @param length
     * @param duplication
     * @return
     */
    public static boolean duplicate(int[] numbers, int length, int[] duplication) {
        if (length <= 1) {
            return false;
        }

        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j++) {
                if (numbers[j] == numbers[i]) {
                    duplication[0] = numbers[i];
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean duplicate1(int[] nums, int length, int[] duplication) {
        if (nums == null || length <= 0) {
            return false;
        }
        for (int i = 0; i < length; i++) {
            while (nums[i] != i) {
                if (nums[i] == nums[nums[i]]) {
                    duplication[0] = nums[i];
                    return true;
                }
                swap(nums, i, nums[i]);
            }
        }
        return false;
    }

    public static void swap(int[] nums, int i, int j) {
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }

    public static void main(String[] args) {
        int[] numbers = {2, 3, 1, 0, 2, 5, 2};
        int[] duplication = new int[1];
        int[] duplication2 = new int[1];
        int[] duplication11 = new int[1];
        boolean duplicate = duplicate(numbers, 7, duplication);
        System.out.println(duplicate);
        System.out.println(duplication[0]);

        boolean duplicate1 = duplicate1(numbers, 7, duplication2);
        System.out.println(duplicate1);
        System.out.println(duplication2[0]);
    }
}

【每日寄语】 当你不开心的时候,你就能够吃一块糖果,而后通知本人生存还是甜甜的,加油。

评论

发表回复

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

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理