Leetcode-剑指Offer03

Kelvin

剑指 Offer 03. 数组中重复的数字

原地交换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
int i = 0;
while(i<nums.size()){
if(i==nums[i]) i++;
else if(nums[i]==nums[nums[i]]){
return nums[i];
}else{
swap(nums[i],nums[nums[i]]);
}
}
return 0;
}
};

利用题目条件在一个长度为 n 的数组 nums 里的所有数字都在 0 ~ n-1 的范围内,可将数值与下标对应起来,当一个下标对应多个数则说明该数为重复的数.

  • Title: Leetcode-剑指Offer03
  • Author: Kelvin
  • Created at: 2023-05-11 20:10:33
  • Updated at: 2023-01-17 02:07:39
  • Link: https://yanwc.com/2023/05/11/2023-01-17-leetcode-offer03/
  • License: This work is licensed under CC BY-NC-SA 4.0.
On this page
Leetcode-剑指Offer03