How to delete an element from int [] in Java?


  • 1
    P

    in removing duplicate, how do I delete an element from int [] in Java?


  • 2

    in the problem, it says "Do not allocate extra space for another array" which means we do not need to create a new int[] array. we can actually "delete" it by shifting the elements after it and return the length of non-duplicate elements.

    public class Solution {
        public int removeDuplicates(int[] A) {
            if (A == null || A.length == 0) {
                return 0;
            }
    
            int index = 0;
            for (int i = 1; i < A.length; i++) {
                if (A[index] == A[i]) {
                    continue;
                } else {
                    A[++index] = A[i];
                }
            }
            return index + 1;
        }
    }
    

  • 0
    J

    Your answer is so simple to understand ,thank you.


  • 0
    H

    A[++index] = A[i]; what does this line mean?


  • 0

    you can consider a simple example. [1,1,2] index=0 and i=1, A[index]=A[i] duplicates exist, so we move pointer i to next element. then for the next loop index=0 and i=2, not duplicates but can not do the in-place for the element A[index], that's why A[++index]


Log in to reply
 

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