剑指Offer : 面试题 3 - 数组中重复的数字

剑指Offer : 面试题 3 - 数组中重复的数字

题目

找出数组中重复的数字

在一个长度为 nn 的数组里的所有的数字都在 n1n-1 的范围内. 数组中某些数字是重复的, 但不知道有几个数字重复了, 也不知道每个数字重复了几次. 请找出数组中任意一个重复的数字.

例,

​ 输入: {2, 3, 1, 0, 2, 5, 3}

​ 输出: 2 或 3

我的解法

思路一

创建一个长度为 nn 数组 aux, 下标 ii 表示数字 ii 出现过的次数. 遍历数组, 如果 aux[i] 的值不等于 0, 则返回当前数字.

时间复杂度: O(n)O(n)

空间复杂度: O(n)O(n)

public class Solution {
  public int repeat(int[] nums) {
    if (nums==null) { return -1; }
    if (nums.length==1) { return -1; }
    int[] aux = new int[nums.length];
    for (int current:nums) {
      if (aux[current]!=0) {
        return current;
      } else {
      	aux[current]++;
      }
    }
    return -1;
  }
}
思路二

将数组排序, 然后遍历数组.

时间复杂度: O(nlogn)O(n\log n)

空间复杂度: O(n)O(n)

public class Solution {
  public int repeat(int[] nums) {
    if (nums==null) { return -1; }
    if (nums.length==1) { return -1; }
    Arrays.sort(nums);
    int current = nums[0];
    for (int i=1; i<nums.length; i++) {
      if (nums[i]==current) {
        return current;
      } else {
        current = nums[i];
      }
    }
    return -1;
  }
}

Arrays.sort() 使用归并排序, 时间复杂度 O(nlogn)O(n\log n), 空间复杂度 O(n)O(n).

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章