|
| 1 | +/* Sure, here's a brief explanation of each solution: |
| 2 | +
|
| 3 | +Solution 1 (O(n) time, O(1) space): |
| 4 | +This solution uses Floyd's Tortoise and Hare algorithm to find the first duplicate value in the array. |
| 5 | +It initializes two pointers, a slow pointer and a fast pointer, to the first value in the array. |
| 6 | +The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. |
| 7 | +When they meet at a certain point, it indicates that there is a cycle in the array. |
| 8 | +Then, the slow pointer is reset to the first value, and both pointers move one step at a time until they meet again, |
| 9 | +which is the start of the cycle (i.e., the first duplicate value in the array). |
| 10 | +
|
| 11 | +Solution 2 (O(n) time, O(n) space): |
| 12 | +This solution uses a HashSet to keep track of the integers that have been seen so far in the array. |
| 13 | +As the array is iterated over, each integer is checked to see if it is already in the set. |
| 14 | +If it is, then it is returned as the first integer that appears more than once. |
| 15 | +If no such integer is found, then -1 is returned. This solution has a time complexity of O(n) and a space complexity of O(n). */ |
| 16 | + |
| 17 | +// Solution 1: O(n) time and O(1) space |
| 18 | +public static int findDuplicate(int[] nums) { |
| 19 | + // iterate through the array |
| 20 | + for (int i = 0; i < nums.length; i++) { |
| 21 | + // calculate the absolute value of the current element |
| 22 | + int val = Math.abs(nums[i]); |
| 23 | + // check if the value at the calculated index is negative |
| 24 | + if (nums[val - 1] < 0) { |
| 25 | + // if it is, return the absolute value of the current element |
| 26 | + return val; |
| 27 | + } |
| 28 | + // otherwise, negate the value at the calculated index |
| 29 | + nums[val - 1] = -nums[val - 1]; |
| 30 | + } |
| 31 | + // if no duplicate is found, return -1 |
| 32 | + return -1; |
| 33 | +} |
| 34 | + |
| 35 | + |
| 36 | +// Solution 2: O(n) time and O(n) space solution: |
| 37 | +public static int findDuplicate(int[] nums) { |
| 38 | + // create a set to keep track of visited elements |
| 39 | + Set<Integer> visited = new HashSet<>(); |
| 40 | + // iterate through the array |
| 41 | + for (int num : nums) { |
| 42 | + // check if the current element has already been visited |
| 43 | + if (visited.contains(num)) { |
| 44 | + // if it has, return the current element |
| 45 | + return num; |
| 46 | + } |
| 47 | + // otherwise, add it to the set of visited elements |
| 48 | + visited.add(num); |
| 49 | + } |
| 50 | + // if no duplicate is found, return -1 |
| 51 | + return -1; |
| 52 | +} |
| 53 | + |
0 commit comments