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 Class1s {

    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;
    }
    }
    //判断并找到数组里存在的重复数字,不能改变输入的数组。
    int begin = 1;
    int end = a.length;
    int middle = 0;
    while(begin <= end){
    middle = (begin + end) / 2;
    int number = calcuNumber(a, begin, middle);
    if(begin == end){
    if(number > 1){
    return begin - 1;
    }else{
    return -1;
    }
    }
    if(number > middle - begin + 1){
    end = middle;
    }else{
    begin = middle + 1;
    }
    }
    System.out.println("数组中没有找到重复的数字!");
    return -1;
    }
    public int calcuNumber(int[] a, int b, int c){
    int number = 0;
    for(int i = 0; i < a.length; i++){
    if((a[i] >= b) && (a[i] <= c)){
    number++;
    }
    }
    return number;
    }
    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    //输入一个数组:
    int[] a1 = {4, 2, 1, 3, 2, 5, 2};
    findRepeatedNumber frn1 = new findRepeatedNumber();
    //输出任意一个重复的数字:
    int r = frn1.findRepeatedNumber(a1);
    if(r > -1){
    System.out.println("数组中重复的数字是:" + a1[r]);
    }
    }
    }

  • 相关阅读:
    Hbase记录-Hbase shell使用
    Hbase记录-Hbase基础概念
    JAVA记录-SpringMVC集成redis
    JAVA记录-redis缓存机制介绍(四)
    JAVA记录-redis缓存机制介绍(三)
    JAVA记录-redis缓存机制介绍(二)
    JAVA记录-redis缓存机制介绍(一)
    JAVA记录-SpringMVC scope属性的两种模式
    JAVA记录-JDBC介绍
    鼠标拖动,改变列表宽度
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12367735.html
Copyright © 2011-2022 走看看