首页 > 其他分享 >剑指Offer03.数组中重复的数字

剑指Offer03.数组中重复的数字

时间:2022-10-13 16:00:25浏览次数:68  
标签:数字 nums 重复 Offer03 int length 数组

1.题目描述

找出数组中重复的数字。

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

2.示例

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3 

3.代码实现及思路

public class Offer03 {
    public static void main(String[] args) {
        int[] nums = {3,3,3,3};
//        System.out.println(nums.length);//0
        Solution03 solution03 = new Solution03();
        int repeatNumber = solution03.findRepeatNumber(nums);
        System.out.println(repeatNumber);

    }
}
class Solution03{
    public int findRepeatNumber(int[] nums){
        //先将数组排序
        Arrays.sort(nums);

        //判断两个特殊情况,LeetCode中找不到则返回-1
        if (nums.length == 0 || nums.length == 1){
            return -1;
        }

        int index = 0;//保存出现重复元素的指针
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i+1]){
                //找到重复的就退出循环
                index = i;
                break;

            } else {
                //没有找到重复元素,则继续比较下一个元素
                continue;
            }
        }
        return nums[index];
    }
}

4.来源

力扣(LeetCode)
链接:https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof

标签:数字,nums,重复,Offer03,int,length,数组
From: https://www.cnblogs.com/y-tao/p/16788438.html

相关文章