剑指offer_数组---数组中重复的数字

简介: 剑指offer_数组---数组中重复的数字

##题目描述

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

##解题思路

1,用额外的空间来给数组里的数字打标签,当发现重复标签的时候说明找到了

2,将数组里的数字放到和自己值相同的索引处,如果发现索引冲突,则说明找到了

##代码实现

/**
 * 
 */
package 数组;
/**
 * <p>
 * Title:Duplicate
 * </p>
 * <p>
 * Description:
 * </p>
 * 
 * @author 田茂林
 * @data 2017年8月26日 上午10:03:34
 */
public class Duplicate {
  // ===========================================================================使用辅助的boolean数组
  public static boolean duplicate(int numbers[], int length, int[] duplication) {
    if (numbers == null || length < 1) {
      return false;
    }
    for (int i = 0; i < duplication.length; i++) { // 数组元素是否超限判断
      if (numbers[i] < 0 || numbers[i] > length - 1) {
        return false;
      }
    }
    boolean[] flag = new boolean[length];
    for (int i = 0; i < length; i++) {
      flag[numbers[i]] = false; // 初始化所有数组元素都是false
    }
    for (int i = 0; i < length; i++) {
      if (flag[numbers[i]] == true) { // 遇到之前修改过的,就说明遇到重复的了
        duplication[0] = numbers[i];
        return true;
      }
      flag[numbers[i]] = true; // 遇到元素就修改为true
    }
    return false;
  }
  // ===========================================================================不使用额外空间
  public static boolean duplicateSuper(int numbers[], int length,
      int[] duplication) {
    if (numbers == null || length < 1) {
      return false;
    }
    for (int i = 0; i < length; i++) {
      if (numbers[i] < 0 || numbers[i] > length - 1) {
        return false;
      }
    }
    for (int i = 0; i < length; i++) {
      while (numbers[i] != i) {
        if (numbers[i] == numbers[numbers[i]]) {   //如果发现不同的索引处有相同的值,说明重复了
          duplication[0] = numbers[i];
          return true;
        }
        exchange(numbers, i, numbers[i]);      //把数字放到和自己值相同的索引处
      }
    }
    return false;
  }
  public static void exchange(int[] array, int i, int j) {
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  public static void main(String[] args) {
    int[] array = { 2, 3, 1, 0, 2, 5, 3 };
    int[] duplication = new int[1];
    System.out.println(duplicate(array, 7, duplication));
  }
}


相关文章
|
6月前
|
算法 C++
剑指offer(C++)-JZ3:数组中重复的数字(算法-排序)
剑指offer(C++)-JZ3:数组中重复的数字(算法-排序)
【剑指offer】- 数组中重复的数字 -48/67
【剑指offer】- 数组中重复的数字 -48/67
|
4月前
|
Java
每日一题《剑指offer》数组篇之数组中重复的数字
每日一题《剑指offer》数组篇之数组中重复的数字
36 0
每日一题《剑指offer》数组篇之数组中重复的数字
|
4月前
LeetCode(1)-找出数组中重复的数字
LeetCode(1)-找出数组中重复的数字
17 0
|
7月前
剑指offer-2.不修改数组找出重复的数字
剑指offer-2.不修改数组找出重复的数字
21 0
|
7月前
剑指offer-1.找出数组中重复的数字
剑指offer-1.找出数组中重复的数字
14 0
|
10月前
剑指offer_数组---数组中只出现一次的数字
剑指offer_数组---数组中只出现一次的数字
50 0
|
10月前
剑指offer_数组---数字在排序数组中出现的次数
剑指offer_数组---数字在排序数组中出现的次数
31 0
|
10月前
剑指offer 02. 不修改数组找出重复的数字
剑指offer 02. 不修改数组找出重复的数字
46 0
|
10月前
|
C++
剑指offer 01. 找出数组中重复的数字
剑指offer 01. 找出数组中重复的数字
35 0

热门文章

最新文章