Given an array of sizen + 1 with elements from 1 to n. One element is duplicated multiple times. Find that element in O(1) space. An array cannot be changed.
publicclassDuplicateNumberDetection {publicintfindDuplicate(int[]nums) {if (nums.length==0|| nums.length==1) {return-1; }int slow= nums[0];int fast= nums[nums[0]];while (slow!= fast) { slow= nums[slow]; fast= nums[nums[fast]]; } fast=0;while (slow!= fast) { slow= nums[slow]; fast= nums[fast]; }return fast; }publicstaticvoidmain(Stringargs[]) {int[] input= {2,1,3,1,5,4};DuplicateNumberDetection dd=newDuplicateNumberDetection();System.out.println(dd.findDuplicate(input)); }}
Output:
1
Comments
Post a Comment