首页 > 其他 > 详细

leetCode 27.Remove Element (删除元素) 解题思路和方法

时间:2015-07-07 22:50:03      阅读:325      评论:0      收藏:0      [点我收藏+]

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.


思路:此题和26题一脉相承,算法上不难,具体如代码所示:

public class Solution {
    public int removeElement(int[] nums, int val) {
        int len = nums.length;
        int tempLen = len;
        int step = 0;//每个元素需要向前转移的距离
        for(int i = 0; i < len; i++){
            if(nums[i] == val){
                step++;//若相等步长+1
                tempLen--;//每一个相等的元素长度减少1
            }else{
                nums[i-step] = nums[i];//元素前移n个步长
            }
        }
        return tempLen;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

leetCode 27.Remove Element (删除元素) 解题思路和方法

原文:http://blog.csdn.net/xygy8860/article/details/46793887

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!