您的位置:首页 > 编程语言 > Java开发

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 =
[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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 算法 leetcode