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.
這道題也很簡單,個人認為,特別是因為只是要求remove,對order的順序也沒有改變(當然了如果愿意還是盡量可以不改變順序)。可以用個簡單的two pointer來解決。一個int用來loop,另一個int則是用來排序剩下的integer。
public class Solution { public int removeElement(int[] nums, int val) { int a = 0; int b = 0; if (nums.length==0){ return 0; } while( b<nums.length ) { if ( nums[b]!=val ) { nums[a] = nums[b]; a++; } b++; } return a; }}
|
新聞熱點
疑難解答