Why has the wrong output with the for loop but the correct output with the while loop?


  • 0
    M

    public class Solution {

    public int removeElement(int[] nums, int val) {
        if (nums == null) {
            return 0;
        }
        int j = nums.length - 1;
    
        for (int i = 0; i <= j; i++) {
            if (nums[j] == val) {
                j--;
                continue;
            }
            if (nums[i] == val) {
                nums[i] = nums[j];
                j--;
            }
        }
        return j + 1;
    }
    

    }

    public class Solution {

    public int removeElement(int[] nums, int val) {
    
        if (nums == null) {
            return 0;
        }
        int i = 0;
        int j = nums.length - 1;
        while (i <= j) {
            if (nums[j] == val) {
                j--;
                continue;
            }
    
            if (nums[i] == val) {
                nums[i] = nums[j];
                j--;
            }
          i++;
        }
        return j + 1;
    }
    

    }


  • 1

    continue skips the i++ of the while-loop but not of the for-loop.


Log in to reply
 

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