首页 > 其他 > 详细

Remove Element Leetcode

时间:2017-01-19 12:12:53      阅读:191      评论:0      收藏:0      [点我收藏+]

Given an array and a value, remove all instances of that value in place and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3]val = 3

Your function should return length = 2, with the first two elements of nums being 2.

Hint:

  1. Try two pointers.
  2. Did you use the property of "the order of elements can be changed"?
  3. What happens when the elements to remove are rare?

 

Subscribe to see which companies asked this question

这道题我真的是。。。

用了传统的双指针,但是如果条件是left < right怎么都不行,换成left <= right就对了。

因为left < right没有考虑[3, 3, 3, 3], 3的情况,这个时候length还是1。所以有没有等号要看一下极端情况。

另外需要注意swap的时候其实也要检查left<=right

public class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null) {
            return 0;
        }
        int left = 0, right = nums.length - 1;
        int l = nums.length;
        while (left <= right) {
            while (left <= right && nums[left] != val) {
                left++;
            }
            while (left <= right && nums[right] == val) {
                right--;
                l--;
            }
            if (left <= right) {
                nums[left] = nums[right];
                left++;
                right--;
                l--;
            }
        }
        return l;
    }
}

反正做出来了,就是代码很长。。。看完人家的top solution,觉得自己的方法真是笨啊。。

public class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null) {
            return 0;
        }
        int n = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[n] = nums[i];
                n++;
            }
        }
        return n;
    }
}

 

Remove Element Leetcode

原文:http://www.cnblogs.com/aprilyang/p/6305723.html

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