3 - Two Pointers Algorithm
521. Remove Duplicate Numbers in Array
总结:数组中比较 + 移除元素问题
public class Solution { /** * @param nums: an array of integers * @return: the number of unique integers */ public int deduplication(int[] nums) { if(nums== null || nums.length == 0) return 0; int left = 0, right = 0; Arrays.sort(nums); int len = nums.length; while(right < len) { if(nums[right] != nums[left]) { nums[++left] = nums[right]; } right++; } return left + 1; } }
484. Sort Integers II
https://www.lintcode.com/problem/sort-integers-ii/description?_from=ladder&&fromId=1
quick sort 是相向双指针。
要点:在进行排序的时候,要用两个while循环将左右位置正确的数字略过。而后双指针值得就是位置不正确的数,于是再交换此时指针所指的数值。
排序中要时刻判断 left <= right,因为每一步操作都会影响到 left 和 right 的值,因此虽然最外层的 while 已经筛选过了,内部散步间依然要再筛选一次。
终止递归的条件是 start >= end,
public class Solution { /** * @param A: an integer array * @return: nothing */ public void sortIntegers2(int[] A) { // write your code here quickSort(A, 0, A.length - 1); } public void quickSort(int[] A, int start, int end) { if(start >= end) return; int left = start, right = end; int pivot = A[(left + right) / 2]; while(left <= right) { while(left <= right && A[left] < pivot) { left++; } while(left <= right && A[right] > pivot) { right--; } if(left <= right) { int temp = A[left]; A[left] = A[right]; A[right] = temp; left++; right--; } } quickSort(A, start, right); quickSort(A, left, end); } }
608. Two Sum II - Input array is sorted
https://www.lintcode.com/problem/two-sum-ii-input-array-is-sorted/description?_from=ladder&&fromId=1
public class Solution { /** * @param nums: an array of Integer * @param target: target = nums[index1] + nums[index2] * @return: [index1 + 1, index2 + 1] (index1 < index2) */ public int[] twoSum(int[] nums, int target) { // write your code here if(nums == null || nums.length == 0) return null; Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++) { int remain = target - nums[i]; if(map.containsKey(remain)) { //System.out.println(remain); return new int[]{map.get(remain) + 1, i + 1}; } if(!map.containsKey(nums[i])) { map.put(nums[i], i); } } return null; } }