目录
283.移动零
题目描述:
解决方法一:
class Solution { public void moveZeroes(int[] nums) { int low = 0 ; int high = nums.length-1; int write = nums.length-1; int i = 0; int arr[] = new int[nums.length]; while(low <= high){ if(nums[low]==0){ arr[write] = nums[low]; low ++ ; write --; }else if(nums[high]==0){ arr[write] = nums[high]; high -- ; write -- ; }else if(nums[low]!=0 && i < arr.length){ arr[i] = nums[low]; i++ ; low ++; } } for(int j = 0 ; j<=arr.length-1 ; j++){ nums[j] = arr[j] ; } } }
解决方法二:
class Solution { public void moveZeroes(int[] nums) { int n = nums.length, left = 0, right = 0; while (right < n) { if (nums[right] != 0) { swap(nums, left, right); left++; } right++; } } public void swap(int[] nums, int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } }
167.两数之和II-输入有序数组
题目描述:
解决方法:
class Solution { public int[] twoSum(int[] numbers, int target) { int high = numbers.length-1; int low = 0 ; int[] arr = new int[2]; while(low < high){ if(numbers[low] + numbers[high]<target){ low++; }else if(numbers[low] + numbers[high]>target){ high--; }else{ arr[0] = low+1 ; arr[1] = high+1; return arr; } } return arr; } }