zoukankan      html  css  js  c++  java
  • 51、数组中重复的数

    题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。

    https://www.nowcoder.com/practice/623a5ac0ea5b4e5f95552655361ae0a8?tpId=13&tqId=11203&tPage=3&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

    思路:

     把数值放到对应的下标下,若对应的下标的元素和该值相等,出现重复。

    注意:检查数组的值在0-n-1内

    public class Solution {
        // Parameters:
        //    numbers:     an array of integers
        //    length:      the length of array numbers
        //    duplication: (Output) the duplicated number in the array number,length of duplication array is 1,so using duplication[0] = ? in implementation;
        //                  Here duplication like pointor in C/C++, duplication[0] equal *duplication in C/C++
        //    这里要特别注意~返回任意重复的一个,赋值duplication[0]
        // Return value:       true if the input is valid, and there are some duplications in the array number
        //                     otherwise false
        public boolean duplicate(int numbers[],int length,int [] duplication) {
            //way1.排序然后遍历时间O(nlogn)
            //way2.hashmap,o(n)的时间,o(n)的空间
            //way3.遍历数组和当前下标比较,并交换放到对于的下标下,直到发现重复的数。o(n)的时间,o(1)的空间
            if (numbers == null || numbers.length == 0) {
                return false;
            }
            for (int i = 0; i < numbers.length; i++) {
                //数字都在0到n-1的范围内
                if (numbers[i] < 0 || numbers[i] >= numbers.length ) {
                    return false;
                }
            }
            for (int i = 0; i < numbers.length; i++) {
                //如果当前值和下标相等,就下一个
                if (numbers[i] == i) {
                    continue;
                }
                //当前值和下标不等,且发现,当前值和对于下标的值相等,发现重复的数
                if (numbers[i] == numbers[numbers[i]]){
                    duplication[0] = numbers[i];
                    return true;
                }
                //将当前值放到对应的下标位置
                int temp = numbers[i];
                numbers[i] = numbers[temp];
                numbers[temp] = temp;
            }
            return false;
        
        }
    }
    View Code

    测试:没有重复的元素;重复的元素有多个;重复的元素是最大或最小;数组元素不在0-n-1

  • 相关阅读:
    使用maven创建web项目
    SSM框架——使用MyBatis Generator自动创建代码
    java中微信统一下单采坑(app微信支付)
    mac的safari浏览器调试h5
    服务端调用高德地图api实现ip定位城市
    mvn打包时,出现数据库连接错误
    其他知识点收集
    linux中项目占用cpu、内存过高时的排查经历
    linux中安装mysql
    linux中jdk的安装与配置
  • 原文地址:https://www.cnblogs.com/lingli-meng/p/7203215.html
Copyright © 2011-2022 走看看