Leetcode-27. Remove Element
2016-10-02 15:22
543 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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 =
Your function should return length = 2, with the first two elements of nums being 2.
这个题目是26题差不多,用两个指针变量就可以解决了,时间复杂度O(n)Your runtime beats 7.78% of java submissions.
博客链接:mcf171的博客
——————————————————————————————
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.
这个题目是26题差不多,用两个指针变量就可以解决了,时间复杂度O(n)Your runtime beats 7.78% of java submissions.
public class Solution { public int removeElement(int[] nums, int val) { if(nums == null) return 0; if(nums.length == 0) return 0; if(nums.length == 1){ if(nums[0] == val) return 0; else return 1; } int slowPoint = 0; int fastPoint = 0; while(fastPoint < nums.length){ if( nums[fastPoint] != val){ nums[slowPoint] = nums[fastPoint]; slowPoint ++; } fastPoint ++; } return slowPoint; } }
相关文章推荐
- [LeetCode-27] Remove Element(从数组删除指定的元素)
- Java [leetcode 27]Remove Element
- Leetcode||27.Remove Element
- LeetCode 27 Remove Element
- 【LeetCode】算法题 27 Remove Element
- 【LeetCode】27 Remove Element
- LeetCode | #27 Remove Element
- LeetCode 27. Remove Element
- LeetCode-27 Remove Element
- [Leetcode 27, easy] Remove Element
- leetcode 27 Remove Element
- [Leetcode] 27. Remove Element
- leetcode 27 Remove Element
- LeetCode 27. Remove Element
- Leetcode 27 Remove Element
- LeetCode 27 : Remove Element
- leetcode 27 -- Remove Element
- leetcode题解-26. Remove Duplicates from Sorted Array && 27. Remove Element
- leetcode 27. Remove Element
- 【leetcode c++】27 Remove Element