Accepted Java Solution using ArrayList


  • -2
    A

    public class Solution {
    public int removeElement(int[] nums, int val) {
    int n = nums.length;

        ArrayList<Integer> listFinal = new ArrayList<Integer>();
        int k = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] != val){
                listFinal.add(nums[i]);
            }
        }
        for ( Integer i :listFinal){
            nums [k++] = i;
        }
        return listFinal.size();
    }
    

    }


  • 0
    B

    This is not an in place solution.


  • 0

    // in the eclipse, show the right answer, but it fail the test case [4,5], 4, any one can help me figure it out?

    public class Solution {
    public int removeElement(int[] nums, int val) {
    int len = nums.length;
    if(len == 0) return 0;
    Arrays.sort(nums);
    ArrayList<Integer> li = new ArrayList<Integer>();
    for(int n : nums){
    if(n != val){
    li.add(n);
    }
    }
    return li.size();
    }
    }


Log in to reply
 

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