【leetcode】287. 寻找重复数
題目鏈接:傳送門
題目描述:
給定一個(gè)數(shù)組 nums 包含 n + 1 個(gè)整數(shù),每個(gè)整數(shù)在 1 到 n 之間,包括 1 和 n?,F(xiàn)在假設(shè)數(shù)組中存在一個(gè)重復(fù)的數(shù)字,找到該重復(fù)的數(shù)字。
注意
樣例
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
算法
(雙指針移動(dòng)) O(n)
因?yàn)槊總€(gè)數(shù)都是 1 到 n,所以此題可以當(dāng)做Linked List Cycle II來(lái)處理。
首先f(wàn)irst和second指針均為0,然后first每次前進(jìn)一格,second每次前進(jìn)兩格。i前進(jìn)一格在這里指的是nums[i]。剩余部分請(qǐng)參考Linked List Cycle II中的算法證明。
時(shí)間復(fù)雜度
參見(jiàn)Linked List Cycle II時(shí)間復(fù)雜度部分,整個(gè)數(shù)組僅遍歷常數(shù)次,故時(shí)間復(fù)雜度為O(n)。
作者:wzc1995
鏈接:https://www.acwing.com/solution/LeetCode/content/302/
?
將數(shù)組轉(zhuǎn)化為鏈表形式:數(shù)組 [1,3,4,2,2]
| current / index | 0 | 1 | 2 | 3 | 4 |
| next / num[index] | 1 | 3 | 4 | 2 | 2 |
?
index為當(dāng)前值的索引,num[index]為下個(gè)一值的索引next index。上表中的數(shù)組表示成鏈表如下圖,方框中為index, num[index]
?
利用【142_環(huán)形鏈表 II】的方法,找到環(huán)入口,即為重復(fù)數(shù)字
設(shè):
slow指針移動(dòng)速度為1,fast指針移動(dòng)速度為2;slow指針在環(huán)內(nèi)移動(dòng)(非環(huán)部分)長(zhǎng)度為a,slow指針在環(huán)內(nèi)移動(dòng)長(zhǎng)度為b
兩指針相遇時(shí)候,slow指針移動(dòng)距離為a+b,fast指針移動(dòng)距離為2(a+b),可知兩指針距離差a+b即為整數(shù)倍的環(huán)長(zhǎng)
從head移動(dòng)a的距離為入環(huán)點(diǎn);由2可知從head開(kāi)始移動(dòng)a+(a+b)的距離也為入環(huán)點(diǎn),即將A點(diǎn)繼續(xù)移動(dòng)距離a則可到達(dá)入環(huán)點(diǎn)
將slow指針移動(dòng)回head,同時(shí)同速移動(dòng)兩個(gè)指針,相遇點(diǎn)即為入環(huán)點(diǎn)
說(shuō)明:
因?yàn)閿?shù)組中不含0,所以不會(huì)因?yàn)閕ndex = 0, num[0] = 0導(dǎo)致死循環(huán);對(duì)于其他位置index = num[index],若該值重復(fù)則會(huì)自身成環(huán),若無(wú)重復(fù)則不會(huì)被遍歷到
作者:LuoRong1994
鏈接:https://leetcode-cn.com/problems/two-sum/solution/287_xun-zhao-zhong-fu-shu-by-user9081a/
?
1 class Solution { 2 public: 3 int findDuplicate(vector<int>& nums) { 4 int cnt = 0 ; 5 int L = 1 , R = nums.size() - 1 , Mid , ans = 0 ; 6 while ( L < R ) { 7 Mid = (L+R) >> 1; 8 cnt = 0 ; 9 for ( int x : nums ) 10 cnt += L <= x && x <= Mid ; 11 if ( Mid - L + 1 < cnt ){ 12 R = Mid ; 13 }else { 14 L = Mid + 1 ; 15 } 16 } 17 return R ; 18 19 } 20 }; 二分做法?
1 class Solution { 2 public: 3 int findDuplicate(vector<int>& nums) { 4 int Fir , Sec ; 5 Fir = Sec = 0 ; 6 do{ 7 Fir = nums[Fir] ; 8 Sec = nums[nums[Sec]] ; 9 }while ( Fir != Sec ); 10 11 Fir = 0; 12 while ( Fir != Sec ){ 13 Fir = nums[Fir] ; 14 Sec = nums[Sec] ; 15 } 16 return Fir; 17 } 18 }; 雙指針?
轉(zhuǎn)載于:https://www.cnblogs.com/Osea/p/11182305.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的【leetcode】287. 寻找重复数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【ABAP系列】SAP 面试 ABAPe
- 下一篇: JQuery .net WebServi