leetcode- Remove Element

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.

最近都没有刷题了,刚上来要先找找感觉。

梳理一下做题思路:

1、审题!这是最先也是最重要的步骤!要明白它的题意,不要漏掉任何条件,关键看它是怎么问的!!!!

2、有思路,逻辑是怎么样的,对应到数学模型。映射到什么数据结构?(这种数据结构对应什么样的通用方法or算法?)有什么算法可以解决?解的形式是怎样的?

3、从数学模型对应到程序,确定方法 ->确定变量种类和数目;

4、编程

     1、测试用例、边界条件放前面

     2、做完以后,想想怎么可以优化?space or time

这道题的思路:使用了两个指针的方式。

代码1:

package leetcode;
//理解题意!!![2,3,3,2] ,val = 3,那么前面保留的是删除后的元素,此方法是把与val相同的元素移到数组后面,把剩下的放到前面,而题目是只要把剩下的放到前就OK啦~!
public class RemoveElement {
    public int removeElement(int[] nums, int val) {
        int m = nums.length;
        
        int p1 = 0;
        int p2 = m-1;
        
        int index = 0;
        while (p1 <= p2) {
            if (nums[p1] == val) {
                if (nums[p2] != val) {
                int    tmp = nums[p2];
                    nums[p2] = nums[p1];
                    nums[p1] = tmp;
                    p1++;
                }
                p2--;
                index++;
            } else {
                p1++;
            }        
        }
        return m - index;
    }
}

仔细理解题目,发现,题目只是把不相同的数都移到数组前面就好,没有说就要把相同的移到后面,所以可以直接将后面的数覆盖到前面,不要理后面。

方法2:

public class Solution {
   public int removeElement(int[] nums, int val) {
    int l = 0, r = nums.length-1;
    while (l <= r) {
        if (nums[l] == val)
            nums[l] = nums[r--];
        else
            l++;
    }
    return l;
}
}

 

posted @ 2016-04-12 19:11  wangb021  阅读(144)  评论(0编辑  收藏  举报