zoukankan      html  css  js  c++  java
  • 剑指offer(Java版)第一题:在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。 *请找出数组中任意一个重复的数字。 *例如,如果输入长度为7的数组{2, 3, 1, 0, 2, 5, 3},那么对应的输出是重复的数字2或者3。

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

    import java.util.*;

    public class Class1 {

    static class findRepeatedNumber{

    public int findRepeatedNumber(int[] a){
    //判断数组是否存在问题
    if(a == null || a.length <= 0){
    System.out.println("输入的数组有误!");
    System.exit(0);
    return -1;
    }
    //判断数组里的数字是否存在问题
    for(int i = 0; i < a.length; i++){
    if(a[i] < 0 || a[i] > a.length){
    System.out.println("数组中的数字存在异常!");
    System.exit(0);
    return -1;
    }
    }
    //判断并找到数组里存在的重复数字
    for(int j = 0; j < a.length - 1; j++){
    //修改数组
    int temp;
    do{
    if(a[a[j]] == a[j]){
    return a[j];
    }
    temp = a[j];
    a[j] = a[temp];
    a[temp] = temp;
    }while(a[j] != j);
    }
    System.out.println("数组中没有找到重复的数字!");
    return -1;
    }

    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    //输入一个数组:
    int[] a1 = {4, 2, 1, 0, 2, 5, 2};
    findRepeatedNumber frn = new findRepeatedNumber();
    //输出任意一个重复的数字:
    int b = frn.findRepeatedNumber(a1);
    if(b > -1){
    System.out.println("数组中重复的数字是:" + b);
    }
    }
    }

  • 相关阅读:
    PHP简单工厂模式、工厂方法模式和抽象工厂模式
    PHP的HashTable实现
    理解Hash
    PHP中Array的hash函数实现
    R-FCN论文讲解(转载链接)
    目标检测的发展历程
    K-means算法
    pytorch0.4.1安装
    反卷积(deconvolution)
    faster-rcnn自己的理解总结(包括它的前世今身R-CNN和fast R-CNN)
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12366697.html
Copyright © 2011-2022 走看看