简体   繁体   English

关于 LeetCode 中算法问题的问题 - Remove Duplicates from Sorted Array using Java

[英]Questions regarding the algorithm question in LeetCode - Remove Duplicates from Sorted Array using Java

I am working on an algorithm problem on Leetcode.我正在研究 Leetcode 上的算法问题。 But first I wrote my answer on my own local compiler.但首先我在我自己的本地编译器上写下了我的答案。 When running my code locally, I can get the answer to this question.在本地运行我的代码时,我可以得到这个问题的答案。 But when I paste my answer directly into the online compiler on leetcode, the system prompts me that my answer is wrong.但是当我将答案直接粘贴到leetcode上的在线编译器中时,系统提示我我的答案是错误的。 Cannot match the correct answer.无法匹配正确答案。 The solution from my local compiler shown below:我的本地编译器的解决方案如下所示:

class Solution {
    public int removeDuplicates(int[] nums) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        ArrayList<Integer> arraylist = new ArrayList<Integer>();

        for (int i : nums) {
            list.add(i);
        }

        for (int num : list) {
            if (!arraylist.contains(num)) {
                arraylist.add(num);
            }
        }

        return arraylist.size();
    }
}

And the feedback from LeetCode: enter image description here以及来自 LeetCode 的反馈:在此处输入图片描述

Some comments say that a set could be used, but the task is to do so without any additional memory allocation, the simplest solution is:一些评论说可以使用一套,但任务是这样做没有任何额外的 memory 分配,最简单的解决方案是:

private static int removeDuplicates(int[] numbers) {
    int size = 0;
    for (int i = 0; i < numbers.length; i++) {
        if (i == 0 || numbers[i - 1] != numbers[i]) {
            numbers[size++] = numbers[i];
        }
    }
    return size;
}

set index to 1, if nums[i] is different from nums[i + 1] then increment index by 1将 index 设置为 1,如果 nums[i] 与 nums[i + 1] 不同,则将 index 增加 1

class Solution {
    public int removeDuplicates(int[] nums) {
        
        int index = 1;
        
        for(int i = 0; i < nums.length - 1; i++){
            if(nums[i] != nums[i + 1]){
                nums[index++] = nums[i + 1];
            }
        }
        return index;
        
    }
}

Don't use List , Set , Map , or anything like that.不要使用ListSetMap或类似的东西。 The data is sorted .数据已排序 Use that!用那个!

Actually, ask yourself how your output is [1, 1] , when you can only return a single int value.实际上,当您只能返回一个int值时,问问自己您的 output 如何是[1, 1] How can you output a list/array with only a single number?你怎么能 output 只有一个数字的列表/数组?

So read the challenge description again, first sentence:所以再读一遍挑战描述,第一句话:

... remove the duplicates in-place ... return the new length. ...就地删除重复项...返回新长度。

Since this is your challenge, I'm not going to write the code.由于这是您的挑战,因此我不打算编写代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM