记录刷题过程。

双指针

这里的双指针我理解的是从两端开始,从而减少循环次数。一般我们循环都是从某一个端点移向另一个端点,如果从两端向中间移动,有点分而治之的思想在里面。例如当你要遍历数组时,正常都是用 for 循环遍历:

  1. for(int i=0; i<arr.length; i++) {
  2. sout(arr[i]);
  3. }

但是用双指针,就从两边开始,会快很多:

  1. // 这里数组arr长度是偶数
  2. int i=0,j=arr.length -1;
  3. while (i<j){
  4. System.out.println(arr[i]);
  5. System.out.println(arr[j]);
  6. i++;
  7. j--;
  8. }

具体在题目中的应用:

题目:盛最多水的容器

链接:https://leetcode-cn.com/problems/container-with-most-water/

用暴力破解法:

  1. public static int f1(int[] nums) {
  2. int r = 0;
  3. for (int i = 0; i < nums.length; i++) {
  4. for (int j = i+1; j < nums.length; j++) {
  5. // i = x1, j = x2 , nums[i] = y1, nums[j] = y2
  6. int x = j - i;
  7. int y = Math.min(nums[i],nums[j]);
  8. r = Math.max(r,x*y);
  9. }
  10. }
  11. return r;
  12. }

用双指针:

  1. public static int f2(int[] nums) {
  2. int r = 0,i = 0,j = nums.length-1;
  3. while (i < j) {
  4. if (nums[i] > nums[j]) {
  5. r = Math.max(r,(j - i) * nums[j--]);
  6. }else {
  7. r = Math.max(r,(j - i) * nums[i++]);
  8. }
  9. }
  10. return r;
  11. }