Remove Element 172

Question

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

The order of elements can be changed, and the elements after the new length don't matter.

Example

Given an array [0,4,4,0,0,2,4,4], value=4

return 4 and front four elements of the array is [0,0,0,2]

Solution

这题本身很简单,用前后两个指针就可以解决。前指针从前往后找第一个值等于elem的元素,后指针从后往前找第一个值不等于elem的元素,交换两个元素的值,直到前指针位置超过后指针为止。

但是有一点需要注意,那就是最后返回的长度需要讨论:

  1. 如果在start==end的地方和val想等,则返回start

  2. 如果在start==end的地方和val不等,则返回start+1

代码如下:

public class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums == null || nums.length == 0){
            return 0;
        }

        int start = 0;
        int end = nums.length - 1;
        while(start < end){
            while(start < end && nums[start] != val){
                start++;
            }

            while(start < end && nums[end] == val){
                end--;
            }

            int temp = nums[start];
            nums[start] = nums[end];
            nums[end] = temp;
        }
         return nums[start] == val? start : start + 1;
    }
}

results matching ""

    No results matching ""