|
@@ -0,0 +1,60 @@
|
|
|
|
|
+package leetcode.p287;
|
|
|
|
|
+
|
|
|
|
|
+import java.util.HashMap;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * @ProjectName: LeetCode
|
|
|
|
|
+ * @FileName: Solution
|
|
|
|
|
+ * @Author: 杨逸
|
|
|
|
|
+ * @Data:2026/3/3 19:50
|
|
|
|
|
+ * @Description: https://leetcode.cn/problems/find-the-duplicate-number/?envType=study-plan-v2&envId=top-100-liked
|
|
|
|
|
+ * 287. 寻找重复数
|
|
|
|
|
+ */
|
|
|
|
|
+public class Solution {
|
|
|
|
|
+ /**
|
|
|
|
|
+ * @param nums
|
|
|
|
|
+ * @return
|
|
|
|
|
+ */
|
|
|
|
|
+ public int findDuplicate(int[] nums) {
|
|
|
|
|
+ return firstMissingPositive(nums);
|
|
|
|
|
+ }
|
|
|
|
|
+ private int hashMapSolution(int[] nums){
|
|
|
|
|
+ HashMap<Integer, Integer> map = new HashMap<>();
|
|
|
|
|
+ for (int num : nums) {
|
|
|
|
|
+ Integer count = map.getOrDefault(num, 0);
|
|
|
|
|
+ if (count!=0) {
|
|
|
|
|
+ return num;
|
|
|
|
|
+ }
|
|
|
|
|
+ map.put(num,count+1);
|
|
|
|
|
+ }
|
|
|
|
|
+ return 0;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 参考第一个缺失正整数的解法
|
|
|
|
|
+ * 假设:数字1应该储存在nums[0],数字2应该储存在nums[1]...
|
|
|
|
|
+ * 将数组调整为符合假设的状态,因为只有一个正整数重复,且nums都是正数,所以重复的数字就是调整后不在合法的位置
|
|
|
|
|
+ * 该解法会修改原数组,不满题目要求,但是可以解
|
|
|
|
|
+ * @param nums
|
|
|
|
|
+ * @return
|
|
|
|
|
+ */
|
|
|
|
|
+ private int firstMissingPositive(int[] nums){
|
|
|
|
|
+ int index = 0;
|
|
|
|
|
+ while (index < nums.length){
|
|
|
|
|
+ if (nums[index] > 0 && nums[index] <= nums.length){
|
|
|
|
|
+ int temp = nums[index];
|
|
|
|
|
+ //如果nums[index]已经在正确的位置上,则跳过
|
|
|
|
|
+ if (nums[index] == nums[temp-1]){
|
|
|
|
|
+ index++;
|
|
|
|
|
+ continue;
|
|
|
|
|
+ }
|
|
|
|
|
+ //将nums[index]放到符合设定的位置
|
|
|
|
|
+ nums[index] = nums[temp-1];
|
|
|
|
|
+ nums[temp-1] = temp;
|
|
|
|
|
+ }else{
|
|
|
|
|
+ index++;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ return nums[nums.length - 1];
|
|
|
|
|
+ }
|
|
|
|
|
+}
|