当前位置:网站首页>Find duplicates [Abstract binary / fast and slow pointer / binary enumeration]
Find duplicates [Abstract binary / fast and slow pointer / binary enumeration]
2022-07-02 02:56:00 【REN_ Linsen】
Look for repetitions
Preface
Keep order and dichotomy / Sensitivity of abstract dichotomy ; Retention ring problem / The sensitivity of the loop to the speed pointer .
One 、 Look for repetitions

Two 、 Abstract dichotomy / Speed pointer / Binary enumeration
package everyday.doublePoint;
// Look for repetitions
public class FindDuplicate {
/* Put yourself in your place , If it has been occupied , Repeated description . This modifies the array , Double pointer ,O(n),O(1) */
public int findDuplicate(int[] nums) {
for (int i = 0; i < nums.length; ) {
if (nums[i] - 1 != i) {
if (nums[nums[i] - 1] == nums[i]) return nums[i];
// Swap places
int t = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = t;
} else ++i;
}
return 1;
}
/* Subject requirements , You cannot modify the array . So either double circulation O(N^2^)/O(1), or hash Record O(N)/O(N). Dichotomy can be done without modifying the array ,O(NlogN)/O(1) Keep order and be sensitive to dichotomy , notice 1-n Associate with dichotomy , Abstract dichotomy .( In fact, both bisection and fast and slow pointers belong to the double pointer type ) The elements in the array are 1-n, Add repeating elements , All together n+1 Elements , The repeating element is 1-n One of the elements in . The interval [1,n] Divided into [1,mid]/[mid,n], Record array is less than or equal to mid Number of elements of cnt, If appear cnt > mid The situation of , It indicates that the repeating element is less than or equal to mid. */
public int findDuplicate2(int[] nums) {
int low = 1, high = nums.length - 1;
while (low < high) {
int mid = low + (high - low >>> 1);
// Find less than or equal to mid Number of elements of .
int cnt = 0;
for (int num : nums) cnt += num > mid ? 0 : 1;
// Abstract decision rules , If it is less than or equal to mid The element of exceeds mid individual , Then repeat the element x <= mid
if (cnt > mid) high = mid;
else low = mid + 1;
}
return low;
}
/* The element belongs to 1-n, common n + 1 Elements , If you take it every time nums[nums[i]] Express :nums[i] Go to the next jump nums[nums[i]]. stay index:1-n Closed loop jump , When you encounter the same element later , Will jump to the same place and continue to move forward , Come again to the 2 A repetition , Jump to the same place in front again . Retaining ring / The sensitivity of the loop to the speed pointer . But here is more than just a decision ring , The next key problem is how to use the fast and slow pointer to determine the entrance of the ring ? See the comments in the code for the solution . */
public int findDuplicate3(int[] nums) {
int fast = nums[nums[0]], slow = nums[0];
while (fast != slow) {
fast = nums[nums[fast]];// Take two steps in the closed loop .
slow = nums[slow];// Take a step in the closed loop .
}
// The fast pointer is the slow pointer 2 Times in the background , Let the length from the starting point to the ring mouth be a, The slow pointer walked in the ring b Meet the fast pointer .
// When we met , Slow down a+b Step , It's almost gone 2(a+b) Step , It can be understood as that the pointer is gone a+b Step , Arrive at the meeting place , And the rest of the a+b Step then walked around k circle .
// Set ring length L, be a+b = kL -> a = kL - b = (k - 1)L + (L - b).
// Let's go from the meeting place c Step to the entrance , be a=(k-1)L+c, So go from the starting point a Step to the entrance , The pointer is just ready to go k-1 circle ( Return to the place of meeting ) & c Step to the entrance
// notes : It can be proved that :K>=1, That is, the fast pointer walked at least one circle to catch up with the slow pointer .
slow = 0;
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return fast;
}
/* Binary enumeration . Think about it , Expand by bit , If you can find repeated elements, each one is 0 still 1, You can get repeated elements . Set the first i position ,nums All numbers expand to 1 The number of is x, hold 1-n All numbers expand to 1 The number of is y, If x > y, Then it means that the repeating element number i Position as 1. */
public int findDuplicate4(int[] nums) {
int n = nums.length, ans = 0;
int bit_max = 31;
while (((n - 1) >> bit_max) == 0) {
bit_max -= 1;
}
for (int bit = 0; bit <= bit_max; ++bit) {
int x = 0, y = 0;
for (int i = 0; i < n; ++i) {
if ((nums[i] & (1 << bit)) != 0) {
x += 1;
}
if (i >= 1 && ((i & (1 << bit)) != 0)) {
y += 1;
}
}
if (x > y) {
ans |= 1 << bit;
}
}
return ans;
/* author :LeetCode-Solution link :https://leetcode.cn/problems/find-the-duplicate-number/solution/xun-zhao-zhong-fu-shu-by-leetcode-solution/ source : Power button (LeetCode) The copyright belongs to the author . Commercial reprint please contact the author for authorization , Non-commercial reprint please indicate the source . */
}
}
summary
1) Keep order and dichotomy / Sensitivity of abstract dichotomy ;
2) Retention ring problem / The sensitivity of the loop to the speed pointer .
reference
[1] LeetCode Look for repetitions
[2] LeetCode Official explanation
边栏推荐
- 結婚後
- 2022-2028 global nano abrasive industry research and trend analysis report
- Analysis of FLV packaging format
- 2022安全员-C证考试题及模拟考试
- Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market
- Missing numbers from 0 to n-1 (simple difficulty)
- Build a modern data architecture on the cloud with Amazon AppFlow, Amazon lake formation and Amazon redshift
- MongoDB非关系型数据库
- Mmsegmentation series training and reasoning their own data set (3)
- What is the function of the headphone driver
猜你喜欢

結婚後
![寻找重复数[抽象二分/快慢指针/二进制枚举]](/img/9b/3c001c3b86ca3f8622daa7f7687cdb.png)
寻找重复数[抽象二分/快慢指针/二进制枚举]

Tupu software has passed CMMI5 certification| High authority and high-level certification in the international software field

Mongodb base de données non relationnelle

2022-2028 global manual dental cleaning equipment industry research and trend analysis report

MMSegmentation系列之训练与推理自己的数据集(三)

Baohong industry | four basic knowledge necessary for personal finance

Which kind of sports headphones is easier to use? The most recommended sports headphones
![[question 008: what is UV in unity?]](/img/f7/5ee0b18d1fe21ff3b98518c46d9520.jpg)
[question 008: what is UV in unity?]

Batch detect whether there is CDN in URL - high accuracy
随机推荐
Multi threaded query, double efficiency
Software testing learning notes - network knowledge
[learn C and fly] 2day Chapter 8 pointer (practice 8.1 password unlocking)
Which brand of sports headset is better? Bluetooth headset suitable for sports
Tupu software has passed CMMI5 certification| High authority and high-level certification in the international software field
2022 low voltage electrician test question simulation test question bank simulation test platform operation
2022 hoisting machinery command examination paper and summary of hoisting machinery command examination
STM32__05—PWM控制直流电机
New programmer magazine | Li Penghui talks about open source cloud native message flow system
[JVM] detailed description of the process of creating objects
[pit] how to understand "parameter fishing"
ZABBIX API creates hosts in batches according to the host information in Excel files
el-table的render-header用法
Special symbols in SAP ui5 data binding syntax, and detailed explanation of absolute binding and relative binding concepts
C write TXT file
Ten minutes will take you in-depth understanding of multithreading - multithreaded teamwork: synchronous control
【做题打卡】集成每日5题分享(第二期)
CVPR 2022 | 大连理工提出自校准照明框架,用于现实场景的微光图像增强
GB/T-2423.xx 环境试验文件,整理包括了最新的文件里面
V-model of custom component