zoukankan      html  css  js  c++  java
  • 数组长度为len,数组元素的范围是0到len-1,找出数组的重复元素

        public static int findDuplicate(int[] nums) {
            int len = nums.length;
            //注意这里的for循环写法,在交换元素后,i没有增加,还要继续进行判断
            for (int i = 0; i < len;) {
                if (nums[i] != i) {
                    //不相等
                    int temp = nums[i];
                    if (temp == nums[temp]) {
                        //相等就返回
                        return temp;
                    }
                    nums[i] = nums[temp]; 
                    nums[temp] = temp; //这里将temp放到对应的位置上
                } else {
                    i++;
                }
            }
            return -1;
        }
    
        public static void main(String[] args) {
            int[] nums = { 1, 2, 4, 2, 3 , 6 , 5};
            System.out.println(findDuplicate(nums));
            
        }
  • 相关阅读:
    hdu-1114
    hdu2546
    POJ-3126
    POJ-1915
    ZOJ-1709
    Codeforces 847H
    Codeforces 847C
    Codeforces 847I
    Codeforces 847E
    算法笔记--矩阵及矩阵快速幂
  • 原文地址:https://www.cnblogs.com/moris5013/p/10648029.html
Copyright © 2011-2022 走看看