当前位置:网站首页>剑指 Offer 03. 数组中重复的数字
剑指 Offer 03. 数组中重复的数字
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
二、解题
原地哈希
将数值放在对应的下标处即可,交换数据,如果出现重复直接放回重复的数据即可。
class Solution {
public int findRepeatNumber(int[] nums) {
//原地哈希
int length = nums.length;
for(int i = 0;i<length;i++){
//如果出现重复 则nums[nums[i]] == nums[i]
while(nums[nums[i]] != i){
//交换数据后,发现重复了,则返回
if (nums[i] == nums[nums[i]]) {
return nums[i];
}
swap(nums,nums[i],i);
}
}
return -1;
}
public void swap(int[] nums,int left,int right){
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hequnwang10/article/details/124211022
边栏推荐
- 01-初识sketch-sketch优势
- 1-5 nodejs commonjs specification
- . net type transfer
- Summary of common SQL statements
- [logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
- Open futures, open an account, cloud security or trust the software of futures companies?
- 索引:手把手教你索引从零基础到精通使用
- [simple understanding of database]
- Net standard
- Baidu Map Case - Zoom component, map scale component
猜你喜欢
索引:手把手教你索引从零基础到精通使用
Qt 修改UI没有生效
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
RPC核心概念理解
[ES6] promise related (event loop, macro / micro task, promise, await / await)
常用SQL语句总结
嵌入式系统中,FLASH中的程序代码必须搬到RAM中运行吗?
[logical fallacy in life] Scarecrow fallacy and inability to refute are not proof
练习:求偶数和、阈值分割和求差( list 对象的两个基础小题)
Compare the performance of query based on the number of paging data that meet the query conditions
随机推荐
Matlab / Simulink simulation of double closed loop DC speed regulation system
1-5 nodejs commonjs specification
1-2 characteristics of nodejs
Learning record of uni app dark horse yougou project (Part 2)
超分之TDAN
Freecodecamp ---- budget & category exercise
Shell-cut命令的使用
Manually implement simple promise and its basic functions
[markdown notes]
Advantages and disadvantages of several note taking software
Indexes and views in MySQL
ASP. Net core configuration options (Part 2)
PC uses wireless network card to connect to mobile phone hotspot. Why can't you surf the Internet
Shell-sed命令的使用
1-2 JSX syntax rules
Allowed latency and side output
Clickhouse table engine
Further study of data visualization
ASP. Net core reads the configuration file in the class library project
Shell - introduction, variables, and basic syntax