剑指offer:03数组中重复的数字

03. 数组中重复的数字

来源:力扣(LeetCode)
链接: https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/

找出数组中重复的数字。

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

示例 1:

输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3 

限制:

2 <= n <= 100000

解题思路:

  • 哈希表:一般碰到找重复的元素,哈希表这种数据结构是非常方便的,且查找速度会非常快;
  • 原地交换:由于数组长度为n,数字大小都在0~n-1范围内,正好与下标index对应,因此可以将元素值与下标进行交换,如果发现nums[nums[i]] == nums[i] 表明该下标上已经有该大小元素的值,有重复的出现,注意这种方式会改变原数组;下标i使用的是while循环,不是for循环,只有当nums[I]==i的时候i才自增;

代码实现

  • 哈希表

    • python实现
    class Solution:
        def findRepeatNumber(self, nums: List[int]) -> int:
            d = dict()
            for num in nums:
                if num not in d:
                    d[num] = ''
                else:
                    return num
            return -1
    
    • c++实现
    class Solution {
    public:
        int findRepeatNumber(vector<int>& nums) {
            unordered_map<int, bool> map;
            for(auto num: nums)
            {
                if(map[num])
                {
                    return num;
                }
                else
                {
                    map[num] = true;
                }
            }
            return -1;
        }
    };
    
  • 原地交换

    • python实现
  class Solution:
      def findRepeatNumber(self, nums: List[int]) -> int:
          n = len(nums)
          i = 0
          while i < n:
              if nums[i] == i:
                  i += 1
                  continue
              if nums[nums[i]] == nums[i]:
                  return nums[i]
              nums[nums[i]], nums[i] = nums[i], nums[nums[i]]
          return -1
  • c++实现
  class Solution {
  public:
      int findRepeatNumber(vector<int>& nums) {
          int n = nums.size();
          int i = 0;
          while(i < n)
          {
              if(nums[i] == i)
              {
                  i++;
                  continue;
              }
              else
              {
                  if(nums[nums[i]] == nums[i])
                  {
                      return nums[i];
                  }
                  else
                  {
                      int temp = nums[nums[i]];
                      nums[nums[i]] = nums[i];
                      nums[i] = temp;
                  }
              }
          }
          return -1;
      }
  };

复杂度分析

  • 时间复杂度:

    • 哈希表: O ( N ) O(N) O(N)
    • 原地交换: O ( N ) O(N) O(N)
  • 空间复杂度:

    • 哈希表: O ( N ) O(N) O(N)
    • 原地交换: O ( 1 ) O(1) O(1)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uncle_ll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值