Weird Answer? Why the expected answer is an array not an integer


  • 1
    K

    The input is [1,1,1,2]

    public class Solution {
        public int removeDuplicates(int[] nums) {
            if(nums == null) return 0;
            if(nums.length == 1) return 1;
            HashMap<Integer,Integer> hm = new HashMap<>();
            for(int i = 0; i < nums.length; i++){
                int temp = nums[i];
                if(hm.containsKey(temp) && hm.get(temp) == 2) continue;
                else if(hm.containsKey(temp) && hm.get(temp) == 1) 
                    hm.put(temp,2);
                else if(!hm.containsKey(temp)) hm.put(temp,1);
            }
            int result = 0;
            for(int i : hm.values()){System.out.println(i);result += i;}
            System.out.print(result);
            return result;
        }
    }
    

    The idea is to use hashmap to store the times one integer appears. I add the two output sentences to
    see the result;

    The stdout is
    2
    1
    3, which means in the final array, there is 2 ones and 1 two, and the length is 3.

    But after running, "Your answer" is [1,1,1] and the "Expected answer" is [1,1,2].

    First, I do not know how this [1,1,1] is obtained.
    Second, it says in the question that "It doesn't matter what you leave beyond the new length".
    Third, the return type of this method is "int", and I return an integer, why the answer is an array?


  • 0

    Did you read/solve the mentioned version I of the problem?

    If you're asked to remove something from an array, do you really think it makes sense to not remove anything from that array?

    The example also does say that you must end "with the first five elements of nums being 1, 1, 2, 2 and 3".


  • 0
    K

    Yes you're right. I solved the I version and wanted to try another method. I just paid too much attention to counting the length of the new array and forgot the requirement of removing duplicates, silly mistake.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.