Leetcode - Remove Elements


Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

[分析] 注意内部while的判断条件有等号,考虑nums]{1}, val=1
public class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0)
            return 0;
        int p = 0, q = nums.length - 1;
        while (true) {
            while (p <= q && nums[p] != val) p++;
            while (p <= q && nums[q] == val) q--;
            if (p < q) {
                nums[p++] = nums[q];
                nums[q] = val;
            } else {
                break;
            }
        }
        return q + 1;
    }
}

猜你喜欢

转载自likesky3.iteye.com/blog/2230517