码迷,mamicode.com
首页 > 其他好文 > 详细

Remove Element

时间:2015-07-24 09:16:36      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

问题描述

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;
    }
}

  

Remove Element

标签:

原文地址:http://www.cnblogs.com/harrygogo/p/4672342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!