Created
April 2, 2026 17:15
-
-
Save thinkphp/901f41f942b887f87a450d2213d2baad to your computer and use it in GitHub Desktop.
find-duplicate-complexitate-logN.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //solution: log n | |
| //n log n (Array.sort(nums)) | |
| //O(n^2) | |
| //O(n) | |
| class Solution { | |
| //[1,3,4,2,2] | |
| //length = 5 | |
| //low = 1; | |
| //high = 5; | |
| public int findDuplicate(int[] nums) { | |
| int low = 1; | |
| int high = nums.length - 1; | |
| //[1,2,3,4,5] | |
| while( low < high ) { | |
| int mid = (low + high) / 2;//1 + 5 = 6/2 = 3 | |
| int count = 0; | |
| for(int num: nums) { | |
| if(num <= mid) { | |
| count++; | |
| } | |
| } | |
| if(count > mid) { | |
| high = mid; | |
| } else { | |
| low = mid + 1; | |
| } | |
| } | |
| return low; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment