我的解法
leetcode27
public static int removeElement(int[] nums, int val) { int last=nums.length-1; int cur=0; while(cur!=nums.length&&last!=cur) { if(nums[cur]==val) { swap(nums,cur,last--); continue; } cur++; } int count=0; for(int i=0;i<nums.length;i++) { if(nums[i]!=val) { count++; } } return count; } public static void swap(int[] arr,int m,int n) { int temp=arr[m]; arr[m]=arr[n]; arr[n]=temp; }
leetcode26
public static int removeDuplicates(int[] nums) { int cur=0; int last=nums.length-1; while(cur<=last) { if(cur!=0&&nums[cur]==nums[cur-1]) { swapAll(nums,cur); last--; continue; } cur++; } int count=0; for(int i=0;i<nums.length;i++) { if(i!=0&&nums[i]>nums[i-1]) { count++; } } return last+1; } public static void swapAll(int[] arr,int cur) { int temp=arr[cur]; for(int i=cur+1;i<=arr.length-1;i++) { arr[i-1]=arr[i]; } arr[arr.length-1]=temp; }
双指针的解法
Leetcode 27
public static int removeElement2(int[] nums, int val) { int i=0; for(int j=0;j<nums.length;j++) { if(nums[j]!=val) { nums[i++]=nums[j]; } } return i; }
解法2
public static int removeElement3(int[] nums, int val) { int i=0; int n=nums.length; while(i<n) { if(nums[i]==val) { nums[i]=nums[--n]; }else { i++; } } return n; }
leetcode 26
public int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; }
学习情况
1次