• 剑指OFFER03-数组中重复的数字


    找出数组中重复的数字。

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

    示例 1:

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

    限制:

    2 <= n <= 100000

    方法一:

    使用Set,遍历数组,如果Set中存在该元素就返回,否则添加到Set中

    public int findRepeatNumber(int[] nums) {
            //方法一:用Set
      			//时间复杂度:O(n) 空间复杂度O(n)
            Set<Integer> set = new HashSet();
            for (int num : nums) {
                if (!set.add(num)){
                    return num;
                }
            }
            return -1;
        }
    

    方法二:

    对数组排序,相同的元素在相邻位置,如果有则返回

    public int findRepeatNumber(int[] nums) {
            //方法二:对数组排序,相同的元素在相邻位置,会修改原来的数组
      			//时间复杂度:O(nlogn) 空间复杂度O(n)
            Arrays.sort(nums);
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == nums[i + 1]) {
                    return nums[i];
                }
            }
            return -1;
        }
    

    方法三:

    利用所有数字都在 0~n-1 的范围内的条件,用一个额外的数组,对每个值就在对应位置+1,当>1的时候返回

    public int findRepeatNumber(int[] nums) {
            //方法三:利用所有数字都在 0~n-1 的范围内的条件,用一个额外的数组,对每个值就在对应位置+1,当>1的时候返回
            int length = nums.length;
            int[] temp = new int[length];
            for (int i = 0; i < length; i++) {
                //对应位置+1
                temp[nums[i]]++;
                //如果大于1,返回
                if (temp[nums[i]] > 1) {
                    return nums[i];
                }
            }
            return -1;
        }
    

    方法四:

    将对应的数值放入数组中的对应位置,如果有重复的返回

    public int findRepeatNumber(int[] nums) {
            //方法四:将对应的数值放入数组中的对应位置
            for (int i = 0; i < nums.length; i++) {
                //如果位置正确,继续
                if (nums[i]== i){
                    continue;
                }
                //如果重复,返回
                if (nums[i]==nums[nums[i]]){
                    return nums[i];
                }
                //交换
                int temp = nums[nums[i]];
                nums[nums[i]] = nums[i];
                nums[i] = temp;
                //交换之后需要原地比较一次
                i--;
            }
            return -1;
    }
    
  • 相关阅读:
    ajax_基础1
    省市数据库脚本TblArea.
    c#中怎么使用dos命
    Lambda表达式
    面试收录
    .Net牛逼程序猿要懂得
    Web.config 配置文件
    sql 查询所有数据库、表名、表字段总结
    Json在net与页面之间的传递
    『转』SAP统驭科目解释
  • 原文地址:https://www.cnblogs.com/jordan95225/p/13524899.html
Copyright © 2020-2023  润新知