[LeetCode] Remove Element

来源:互联网 发布:caffe训练模型 编辑:程序博客网 时间:2024/06/06 03:45

题目

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.

思路

这道题考察的是Two Pointers。用两个指针begin和end分别指向数组的头和尾,begin向后遍历:

1)如果遇到值为val的元素,则该元素和end位置的元素交换,end--

2)否则,begin++


代码

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


0 0