当前位置:网站首页>To Offer | 03. Repeat Numbers in the array
To Offer | 03. Repeat Numbers in the array
2022-08-04 22:19:00 【Lonely Wild Crane】
The sword refers to Offer 03. Repeated numbers in an array - LeetCode(LeetCode)https://leetcode.cn/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/Open a pit today and brush a wave of sword offers (although I have brushed a little bit...
Method 1: Make use of the features of HashSet that can be quickly searched, put elements into HashSet and compare.
class Solution {public int findRepeatNumber(int[] nums) {HashSet integers = new HashSet<>();for (int i = 0; i < nums.length; i++) {if (integers.contains(nums[i])) {return nums[i];}integers.add(nums[i]);}return -1;}}
Method 2: Subscript method, constantly exchange elements so that the elements are the same as their corresponding subscripts until a conflict occurs.
class Solution {public int findRepeatNumber(int[] nums) {// loop through the arrayfor(int i = 0; i < nums.length; i++) {// The reason for using while is because after the swap, the element at that position is still not in the correct positionwhile(i != nums[i]){if(nums[i] == nums[nums[i]]){return nums[i];}// nums[i] is in the correct position at nums[nums[i]]int k = nums[nums[i]];nums[nums[i]] = nums[i];nums[i] = k;}}return -1;}}
边栏推荐
- 2022精选最新金融银行面试真题——附带答案
- BUG | The interface returns abnormal data
- Latex fast insert author ORCID
- 双非读者,一举拿下阿里、字节、美团、京东、虾皮offer
- 【组成原理 六 存储器类型】
- Develop your own text recognition application with Tesseract
- [Linear Algebra 02] 2 interpretations of AX=b and 5 perspectives of matrix multiplication
- Redis中的LRU算法
- UDP communication
- 【C - 基本概念】
猜你喜欢
随机推荐
What does Xinchuang mean?Which industries are involved?Why develop Xinchuang?
Debian防火墙的开关以及状态
快速web开发框架——learun framework
Rocketchip RISC-V Debug调试硬件相关(四)hartIsInReset
用Tesseract开发一个你自己的文字识别应用
【组成原理 六 存储器类型】
力扣19-删除链表的倒数第 N 个结点——链表
ANT1.7 download and configuration method
DREAMWEAVER8 部分问题解决方案
Latex快速插入作者ORCID
Latex fast insert author ORCID
CPU、内存、显卡等硬件因素也影响着你的深度学习模型性能
基于事实的讨论
2022精选最新金融银行面试真题——附带答案
如何在项目中正确使用WebSocket
基于事实的结果
The upgrade and transformation plan of the fortress machine for medium and large commercial banks!Must see!
# #ifndef/#define/#endif使用详解
Redis中的LRU算法
最温馨的家园