Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

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

I am working on an algorithm problem on 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. 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...