Remove Element

问题描述

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. 

 

解决思路

双指针,起始状态两个指针p和q指向首元素,指针p指向的位置表示在此之前的元素均为正常元素(不被移除的)。

如果p指向的元素为正常元素,则p和q均向前一步;否则,找到第一个q指向的正常元素作交换。

注意控制边界条件,防止指针越界。

 

程序

public class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int len = nums.length;
        int p = 0, q = 0;
        while (p < len && q < len) {
            if (nums[p] != val) {
                ++p;
                ++q;
                continue;
            }
            while (q < len && nums[q] == val) {
                ++q;
            }
            if (q == len) {
                break;
            }
            // swap q and p
            int tmp = nums[p];
            nums[p] = nums[q];
            nums[q] = tmp;
        }
        return p;
    }
}

  

posted @ 2015-07-24 08:33  Chapter  阅读(124)  评论(0编辑  收藏  举报