【LeetCode】27.Remove Element(Easy)解题报告
来源:互联网 发布:k歌之王65首歌名知乎 编辑:程序博客网 时间:2024/05/21 18:35
【LeetCode】27.Remove Element(Easy)解题报告
题目地址:https://leetcode.com/problems/remove-element/description/
题目描述:
Given an array and a value, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:Given nums = [3,2,2,3], val = 3,Your function should return length = 2, with the first two elements of nums being 2.
这道题开始不知道到底要求返回什么,但是题里显示返回int,应该是新长度len,但是返回新长度的同时,数组前len个元素也要存新数组的元素。两种方法。
Solution1:用的two pointer。我感觉精髓的地方就是调换元素之后,调换后还可能是val,但是这里他还会看是否相等,不等时begin才会++。
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]; end--; }else{ begin++; } } return end+1; }}
Solution2:既然不可以新开数组,肯定原数组存新信息。那么逛街在于if(nums[i]!=val)。
class Solution { public int removeElement(int[] nums, int val) { int i = 0; for(int j=0;j<nums.length;j++){ if(nums[j]!=val){ nums[i]=nums[j]; i++; } } return i; }}
Date:2017年11月27日
阅读全文
0 0
- 【LeetCode】27.Remove Element(Easy)解题报告
- [leetcode] 27. Remove Element 解题报告
- [Leetcode] 27. Remove Element 解题报告
- LeetCode Remove Element 解题报告
- LeetCode解题报告--Remove Element
- [LeetCode] Remove Element 解题报告
- 【LeetCode】Remove Element 解题报告
- Leetcode Remove Element解题报告
- LeetCode解题报告 169. Majority Element [easy]
- leetcode 27. Remove Element (EASY)
- Leetcode #27. Remove Element 移除元素 解题报告
- Leetcode 27. Remove Element (Easy) (cpp)
- Leetcode 27. Remove Element (Easy) (java)
- [Leetcode 27, easy] Remove Element
- <LeetCode><Easy> 28 Remove Element
- 27. Remove Element [easy]
- 27. Remove Element (Easy)
- 27. Remove Element [easy] (Python)
- linux基础系统目录
- scrapy实战爬取电影天堂相关信息
- 欢迎使用CSDN-markdown编辑器
- php debug 安装配置
- Python中的字符串
- 【LeetCode】27.Remove Element(Easy)解题报告
- 【Scikit-Learn 中文文档】半监督学习
- 106张图为证,配置SSLVPN服务
- Action的三种访问方式(八)
- 私有云落地解决方案之openstack高可用(pike版本)-环境配置
- 13. Roman to Integer题目和答案详解
- 深度优先算法(DFS)遍历有向无环图计算最优路径
- 1.0-springboot的java配置方式
- 给键盘按键带上音效