find-all-duplicates-in-an-array(典型的数组中的重复数,不错,我做出来了,可是发现别人有更好的做法)

https://leetcode.com/problems/find-all-duplicates-in-an-array/

典型的数组中的重复数。这次是通过跳转法,一个个跳转排查的。因为查过的不会重复处理,所以复杂度也是O(n)。

 

后面发现了别人一个更好的做法。。。如下:

复制代码
public class Solution {
    // when find a number i, flip the number at position i-1 to negative. 
    // if the number at position i-1 is already negative, i is the number that occurs twice.
    
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < nums.length; ++i) {
            int index = Math.abs(nums[i])-1;
            if (nums[index] < 0)
                res.add(Math.abs(index+1));
            nums[index] = -nums[index];
        }
        return res;
    }
}
复制代码

 

我的做法:

复制代码
package com.company;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> list = new ArrayList<>();
        int index = 1;
        while (index <= nums.length) {
            int next = nums[index-1];
            nums[index-1] = -1;
            while (next != -1 && next != index && -1 != nums[next-1] && next != nums[next-1]) {
                int tmp = nums[next-1];
                nums[next-1] = next;
                next = tmp;
            }

            if (next == -1) {
            }
            if (next == index) {
                nums[index-1] = next;
            }
            else if (-1 == nums[next-1]) {
                nums[next-1] = next;
            }
            else {
                list.add(next);

            }
            index++;
        }
        return list;
    }

}

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello!");
        Solution solution = new Solution();

        int[] nums = {};
        List<Integer> ret = solution.findDuplicates(nums);
        System.out.printf("ret len is %d\n", ret.size());
        Iterator iter = ret.iterator();
        while (iter.hasNext()) {
            System.out.printf("%d,", iter.next());
        }
        System.out.println();

    }
}
复制代码

 

posted @   blcblc  阅读(592)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示