1. 程式人生 > >LeetCode記錄之27——Remove Element

LeetCode記錄之27——Remove Element

length nbsp pub his 改變 int 兩個 常量 ==

這道題跟26題很類似,並且有官方的答案。看了官方的答案之後發現寫得特別巧,自己做的題太少思路太窄。有意思的是我的算法的時間復雜度是O(N^2),官方的是O(N),我的實際運行時間還少了2ms。

iven 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.

給定一個數組和一個值,刪除該值的所有實例,並返回新的長度。

不要為另一個數組分配額外的空間,您必須使用常量內存來執行此操作。

元素的順序可以改變。 無論你離開新的長度什麽都不重要。

例:
給定輸入數組nums = [3,2,2,3],val = 3

你的函數應該返回length = 2,num的前兩個元素為2。


我的實現算法:

 1 class Solution {
 2     public int removeElement(int[] nums, int val) {
 3     int index=1,count1=0,count2=0;
 4         for(int i=0;i<nums.length;i++){
 5             if(nums[i]==val){
 6                 for(int j=i;j<nums.length;j++){
 7                     int temp=0;
 8                     if
(nums[j]!=val){ 9 temp=nums[j]; 10 nums[j]=nums[i]; 11 nums[i]=temp; 12 count2++; 13 break; 14 } 15 } 16 } 17 else 18 count1++; 19 } 20 return count1+count2; 21 } 22 }

官方的實現算法:

 1 class Solution {
 2     public int removeElement(int[] nums, int val) {
 3     int i = 0;
 4     for (int j = 0; j < nums.length; j++) {
 5         if (nums[j] != val) {
 6             nums[i] = nums[j];
 7             i++;
 8         }
 9     }
10     return i;
11 }
12 }

LeetCode記錄之27——Remove Element