首页 > 其他 > 详细

Remove Element

时间:2015-07-24 09:13:20      阅读:170      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!