Easy-题目28:27.Remove Element

来源:互联网 发布:mysql slow.log 删除 编辑:程序博客网 时间:2024/05/22 06: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.
题目大意:
给一个数组,删除指定元素,并且返回剩下的数组长度。原数组的顺序可以改变。新长度以后的数据是无关紧要的。
题目分析:
使用Java STL中的ArrayList存储数组,遇到指定元素则跳过一次,再遍历ArrayList,把删除后的数组存回原数组,返回ArrayList的长度。
源码:(language:java)

public class Solution {    public int removeElement(int[] nums, int val) {        ArrayList<Integer> list=new ArrayList<Integer>();        for(int i=0;i<nums.length;i++) {            if(nums[i]!=val)                list.add(nums[i]);        }        for(int i=0;i<list.size();i++)            nums[i]=list.get(i);        return list.size();    }}

成绩:
2ms,beats 0.74%,众数1ms,67.19%
cmershen的碎碎念:
这道题也得到了一个很差的成绩,原因是使用了开销比较大的STL,且重复了两次写数组。可以通过two pointer的思想改进一下,一个指针指向待存位置,一个指针指向正在扫描的位置,这样仅需一次读写数组。此外,该题的tag中提示了two pointer,以后在做题时tag的信息应予以注意,因为是很好的提示。

0 0
原创粉丝点击