您的位置:首页 > 其它

[Leetcode 2] 27 Remove Element

2013-04-06 13:30 337 查看
Problem:

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.

Analysis:

Use two pointers, ptrA points to the next-valid-to-copy place; ptrB go through the input array, if *ptrB equals the given value K, skip this position else copy it to *(++ptrA) position. Considering some special case: 1. A=[], K=anyValue, need to return 0; 2. A=[k, k, k] K=k, need to return 0;

The time complexity is O(n) and the space complexity is O(n)

Code:

public class Solution {
public int removeElement(int[] A, int elem) {
// Start typing your Java solution below
// DO NOT write main() function
//if (A.length == 0) return 0;

int a=0;
for (int b=0; b<A.length; b++) {
if (A[b] != elem) {
A[a++] = A[b];
}
}

return a;
}
}


Attention:

Since here A always point to the next-to-copy place, the special case A = [] can be merged into the general solution
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: