`

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;
    }
}
分享到:
评论
1 楼 qb_2008 2015-07-29  
因为在最后的时候,q必须指向一个非val的元素。如果while中没有等号,这个条件就可能不成立。

相关推荐

Global site tag (gtag.js) - Google Analytics