Remove Element

来源:互联网 发布:酷狗音乐无法使用网络 编辑:程序博客网 时间:2024/04/29 17:41
题目描述
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.

解题思路
将提供的元素去掉,并返回剩余数组的长度。

注意问题
1 注意不是只要求返回剩余数组的长度,而且必须是将元素都移动到数组的长度以内。
2 注意去除了多少个元素,就将元素前移几位。

代码示例
package leetcode;import java.util.Arrays;public class RemoveElement {public int removeElement(int[] A, int elem) {int sum = 0;for(int i = 0 ; i < A.length ; i++){if(A[i] == elem) sum++;else A[i-sum] = A[i];}        return A.length-sum;    }public static void main(String[] args) {int[] A = {1, 2, 1, 3, 4};int elem = 2;RemoveElement re = new RemoveElement();System.out.println(re.removeElement(A, elem));}}
0 0
原创粉丝点击