LeetCode题解:Remove Element

来源:互联网 发布:119手游网 92kaifa源码 编辑:程序博客网 时间:2024/05/17 09:26

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.

题意:给定一个数组与一个值,将数组中与该值相同的元素换为其他不同的元素,返回没有该值的长度。

解题思路:双指针,一个在头,一个在尾

代码:

public class Solution {    public int removeElement(int[] A, int elem) {        int len = A.length;        for (int i=0; i < len; i++) {            if (A[i] == elem) {                A[i--] = A[len-- -1];            }        }        return len;    }}
0 0
原创粉丝点击