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
- Easy-题目28:27.Remove Element
- 27. Remove Element [easy]
- 27. Remove Element (Easy)
- 27. Remove Element [easy] (Python)
- leetcode 27. Remove Element (EASY)
- 27. Remove Element 难度:easy
- <LeetCode><Easy> 28 Remove Element
- Leetcode 27. Remove Element (Easy) (cpp)
- Leetcode 27. Remove Element (Easy) (java)
- 【LeetCode】27.Remove Element(Easy)解题报告
- Remove Element(easy)
- [Leetcode 27, easy] Remove Element
- Easy 27题 Remove Element
- Leet Code OJ 27. Remove Element [Difficulty: Easy]
- [LeetCode] 027. Remove Element (Easy) (C++)
- 【LeetCode】2(7)Remove Element(Easy)
- LeetCode-27-Remove Element(数组)-Easy
- Easy 8 Remove Element(27)
- Lexicographical order, dictionary order, permutation
- hdu 1595 find the longest of the shortest(dijkstra)
- Flume+Hadoop+Hive的离线分析系统基本架构
- 深入浅出Mybatis-分页
- Easy-题目27:107.Binary Tree Level Order Traversal II
- Easy-题目28:27.Remove Element
- 69道Spring面试题和答案
- 用SharedPreferences存储数据
- WebService服务中,将写原始报文日志的功能由单独线程处理
- C++独孤九剑第一式——拨云见日(对象内存模型)
- 有关filter
- 视图调用控制器的方法
- Easy-题目29:26. Remove Duplicates from Sorted Array
- C语言课设-1