class Solution { public int findDuplicate(int[] nums) { int slow = nums[0]; int fast = nums[0]; // 找到环 do{ slow = nums[slow]; fast = nums[nums[fast]]; }while(slow!=fast); slow = nums[0]; while(slow!=fast){ slow = nums[slow]; fast = nums[fast]; } return slow; } }
3- ACM 实现
public class duplicateNum { public static int findDuplicate(int[] nums){ // 快慢指针 int slow = nums[0]; int fast = nums[0]; // 出发 do{ slow = nums[slow]; fast = nums[nums[fast]]; }while(slow!=fast); slow = nums[0]; while(slow!=fast){ slow = nums[slow]; fast = nums[fast]; } return slow; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = new int[n]; for(int i = 0 ; i < n;i++){ nums[i] = sc.nextInt(); } System.out.println("结果是"+findDuplicate(nums)); } }