您的位置:首页 > 其它

Leetcode 27. Remove Element & 26. Remove Duplicates from Sorted Array

2016-03-05 04:36 483 查看


27. Remove Element

Total Accepted: 104678 Total
Submissions: 316609 Difficulty: Easy

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.

Method 1: 自己写的 start是第一个放置位置,end是用来取后面的第一个用来shift的元素。

public class Solution {
public int removeElement(int[] nums, int val) {
if (nums == null || nums.length == 0) return 0;

int start = 0;
int end = nums.length - 1;
int count = 0;

while(start<=end)
{
if(nums[start]==val){
count++;
while(end>start && nums[end]==val){
end--;
count++;
}
if (end == start) return nums.length-count;
nums[start++] = nums[end--];
}else{
start++;
}
}
return nums.length-count;
}
}


Method 2: 看了别人的解感觉自己写的就是个渣... 那么多edge case,一不小心就错了,

别人的代码就这么几行,简洁+快速。

public class Solution {
public int removeElement(int[] A, int elem) {
int p = 0;
for (int i = 0; i < A.length; i++)
if (A[i] != elem) A[p++] = A[i];
return p;
}
}



26. Remove Duplicates from Sorted Array

Total Accepted: 116405 Total
Submissions: 353134 Difficulty: Easy

Given a sorted array, remove the duplicates in place such that each element appear only once
and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,

Given input array nums =
[1,1,2]
,
Your function should return length =
2
,
with the first two elements of nums being
1
and
2


有了上一题的经验,这题好做多了 !

public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length ==0) return 0;

int pos=1;

for (int i=1; i<nums.length; i++)
{
if (nums[i]==nums[pos-1]) continue;
nums[pos++]=nums[i];
}
return pos;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: