【LeetCode】Remove Element解題レポート
1145 ワード
Remove Element
[LeetCode]
https://leetcode.com/problems/remove-element/
Total Accepted: 115693 Total Submissions: 341766 Difficulty: Easy
Question
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.
Ways
学問の経験.新しい配列が必要ですが、戻り値は配列の長さで、この配列の長さは元の配列の中で前から数が長いことを意味します.つまり元の基礎の上でどれだけの部分を切り取るかということです.
AC:1ms
Date
2016/5/3 11:29:08
[LeetCode]
https://leetcode.com/problems/remove-element/
Total Accepted: 115693 Total Submissions: 341766 Difficulty: Easy
Question
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.
Ways
学問の経験.新しい配列が必要ですが、戻り値は配列の長さで、この配列の長さは元の配列の中で前から数が長いことを意味します.つまり元の基礎の上でどれだけの部分を切り取るかということです.
public class Solution {
public int removeElement(int[] nums, int val) {
int head=0;
int tail=nums.length;
while(head!=tail){
if(nums[head]==val){
nums[head]=nums[tail-1];
tail--;
}else{
head++;
}
}
return tail;
}
}
AC:1ms
Date
2016/5/3 11:29:08