27. Remove Element
来源:互联网 发布:js回车事件 编辑:程序博客网 时间:2024/06/16 03:41
题目描述
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 in place with constant memory.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3], val = 3
Your function should return length = 2, with the first two elements of nums being 2.
去除所有例子中的值,返回一个新的长度,不要分配额外的空间给另外的数组,你必须做这个在连续的内存,要求值能够被改变。
思路
第一种解法:
删除那个出现的那个值,返回长度。循环,找到就删,但是长度减一,最后面的找不了了,找到打标记最后删,需要开辟一个数组。因此想了一个办法,找到就删除,遍历的时候 从第一个重新开始。
class Solution {public: int removeElement(vector<int>& nums, int val) { int i; for(i = 0; i < nums.size(); i++) { if(nums[i] == val) { nums.erase(nums.begin()+i); i = -1; } } return nums.size(); }};
第二种解法:
j是不相等的数组的长度,不相等的话,前面的就被替换。
class Solution{ public: int removeElement(int A[],int n,int elem) { int i = 0; int j = 0; for(i = 0;i < n;i++) { if(A[i] != elem) { A[j++]=A[i];//不相等的话就赋给j } } return j; } };
第三种解法:
如果与val相等,那么将最后一个值赋给当前的i,然后长度减一,从i这边再次判断,不相等,数组下标往前移动。
public int removeElement(int[] nums, int val) { int i = 0; int n = nums.length; while (i < n) { if (nums[i] == val) { nums[i] = nums[n - 1]; // reduce array size by one n--; } else { i++; } } return n;}
阅读全文
0 0
- [LeetCode]27.Remove Element
- LeetCode --- 27. Remove Element
- LeetCode 27.Remove Element
- [Leetcode] 27. Remove Element
- 27.Remove Element
- [Leetcode] 27.Remove Element
- 27. Remove Element
- 27. Remove Element
- 【leetcode】27. Remove Element
- 【leetcode】27. Remove Element
- 27. Remove Element
- 27. Remove Element
- 27. Remove Element
- Leetcode 27. Remove Element
- 27. Remove Element
- LeetCode 27. Remove Element
- 27. Remove Element LeetCode
- 27. Remove Element
- c语言实现单链表基础面试题
- javascript中if(变量)与if(变量==true)的区别
- 虚拟机里查询ip的方式
- excle转xml文件
- Js面向对象的个人理解
- 27. Remove Element
- 有点小奇怪
- 不使用ES6 语法糖
- Codeforces 475D CGCDSSQ 题解
- 提高单机短连接QPS到20万
- 【MongoDB】Shard key
- Java机器学习库ML之四模型训练和预测示例
- 数据存储之文件存储
- 欢迎使用CSDN-markdown编辑器