Leetcode 题解 - 双指针

双指针: 有序数组  字符串翻转  环形链表问题

算法思想

双指针

双指针主要用于遍历数组,两个指针指向不同的元素,从而协同完成任务。

有序数组的 Two Sum

1 Leetcode :167. Two Sum II - Input array is sorted (Easy)

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

题目描述:在有序数组中找出两个数,使它们的和为 target。

使用双指针,一个指针指向值较小的元素,一个指针指向值较大的元素。指向较小元素的指针从头向尾遍历,指向较大元素的指针从尾向头遍历。

  • 如果两个指针指向元素的和 sum == target,那么得到要求的结果;
  • 如果 sum > target,移动较大的元素,使 sum 变小一些;
  • 如果 sum < target,移动较小的元素,使 sum 变大一些。

public int[] twoSum(int[] numbers, int target) {

    int i = 0, j = numbers.length - 1;

    while (i < j) {

        int sum = numbers[i] + numbers[j];

        if (sum == target) {

            return new int[]{i + 1, j + 1};

        } else if (sum < target) {

            i++;

        } else {

            j--;

        }

    }

    return null;

}

2  633. Sum of Square Numbers (Easy)

Input: 5

Output: True

Explanation: 1 * 1 + 2 * 2 = 5

题目描述:判断一个数是否为两个数的平方和。

public boolean judgeSquareSum(int c) {

    int i = 0, j = (int) Math.sqrt(c);

    while (i <= j) {        关键是相等的这一部分

        int powSum = i   i  +  j  *  j;

        if (powSum == c) {

            return true;

        } else if (powSum > c) {

            j--;

        } else {

            i++;

        }

    }

    return false;

}

反转字符串中的元音字符

3  345. Reverse Vowels of a String (Easy)

Given s = "leetcode", return "leotcede".

使用双指针指向待反转的两个元音字符,一个指针从头向尾遍历,一个指针从尾到头遍历。

private final static HashSet<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));

Hashset的应用 Arrays.asList

public String reverseVowels(String s) {

    int i = 0, j = s.length() - 1;

    char[] result = new char[s.length()];

    while (i <= j) {

        char ci = s.charAt(i);

        char cj = s.charAt(j);

        if (!vowels.contains(ci)) {

            result[i++] = ci;

        } else if (!vowels.contains(cj)) {

            result[j--] = cj;

        } else {

            result[i++] = cj;

            result[j--] = ci;

        }

    }

    return new String(result);  String函数的用法参数可以放到result

}

If,  else if,  else 这些逻辑搞清楚 一次只能完成一部 否则会因为

4  680. Valid Palindrome II (Easy)

Input: "abca"

Output: True

Explanation: You could delete the character 'c'.

题目描述:可以删除一个字符,判断是否能构成回文字符串。

public boolean validPalindrome(String s) {

    for (int i = 0, j = s.length() - 1; i < j; i++, j--) {

        if (s.charAt(i) != s.charAt(j)) {

            return isPalindrome(s, i, j - 1) || isPalindrome(s, i + 1, j);

        }

    }

    return true;

}

private boolean isPalindrome(String s, int i, int j) {

    while (i < j) {

        if (s.charAt(i++) != s.charAt(j--)) {

            return false;

        }

    }

    return true;

}

 

5  88. Merge Sorted Array (Easy)

Input:

nums1 = [1,2,3,0,0,0], m = 3

nums2 = [2,5,6],       n = 3

 

Output: [1,2,2,3,5,6]

题目描述:把归并结果存到第一个数组上。

需要从尾开始遍历,否则在 nums1 上归并得到的值会覆盖还未进行归并比较的值。

本方法是下一个方法的改进  其实在nums1中留出足够空位之后,按双指针在任意一个数组中的排列是不会对数据产生影响的因为大的值已经被安排在后面的空位上,指针后面的值即使被占用也是按顺序排位之后的

class Solution {

    public void merge(int[] nums1, int m, int[] nums2, int n) {

        int index1 = m-1, index2 = n-1, index = m + n -1;

        while(index1 >= 0 || index2 >= 0){

            if(index1 < 0)

                nums1[index--] = nums2[index2--];

            else if(index2 < 0)

                nums1[index--] = nums1[index1--];

            else if(nums1[index1] > nums2[index2])

                nums1[index--] = nums1[index1--];

            else

                nums1[index--] = nums2[index2--];

        }

    }

}

 

class Solution { 好想的方法 引入额外空间

    public void merge(int[] nums1, int m, int[] nums2, int n) {

        int index1 = 0, index2 = 0, index=0;

        int merge = m + n;

        int[] arr = new int[merge];

        while(index1 < m || index2 < n){

            if(index1 == m)

                arr[index++] = nums2[index2++];

            else if(index2 == n)

                arr[index++] = nums1[index1++];

            else if(nums1[index1] < nums2[index2])

                arr[index++] = nums1[index1++];

            else

                arr[index++] = nums2[index2++];

        }

        for(int i=0; i < merge; i++){

            nums1[i] = arr[i];

        }

    }

}

 

判断链表是否存在环

6  141. Linked List Cycle (Easy)

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

 

Example 1:

Input: head = [3,2,0,-4], pos = 1  Output: true  Explanation: There is a cycle in the linked list, where tail connects to the second node.

 

Example 2:

Input: head = [1,2], pos = 0Output: trueExplanation: There is a cycle in the linked list, where tail connects to the first node.

 

Example 3:

Input: head = [1], pos = -1Output: falseExplanation: There is no cycle in the linked list.

 

使用双指针,一个指针每次移动一个节点,一个指针每次移动两个节点,如果存在环,那么这两个指针一定会相遇。

public boolean hasCycle(ListNode head) {

    if (head == null) {

        return false;

    }

    ListNode l1 = head, l2 = head.next;

    while (l2 != null && l2.next != null) {

        if (l1 == l2) {

            return true;

        }

        l1 = l1.next;

        l2 = l2.next.next;

    }

    return false;

}

/**

 * Definition for singly-linked list.

 * class ListNode {

 *     int val;

 *     ListNode next;

 *     ListNode(int x) {

 *         val = x;

 *         next = null;

 *     }

 * }

 */

public class Solution {

    public boolean hasCycle(ListNode head) {

        if(head == null || head.next == null)

            return false;

        ListNode l1 = head;

        ListNode l2 = head.next;

        while(l2!= null && l2.next != null){  由于要判断是不是环形 l1 可以不判断,因为环形的话l2经过的所有节点肯定不为空

            if(l1 == l2)

                return true;

            l1= l1.next;

            l2= l2.next.next;

        }

        return false;

        

        

    }

}

 

最长子序列

524. Longest Word in Dictionary through Deleting (Medium)

记住字典顺序的比较就可以了

Input:

s = "abpcplea", d = ["ale","apple","monkey","plea"]

 

Output:

"apple"

题目描述:删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。

public String findLongestWord(String s, List<String> d) {

第一部分 遍历d 看s一次是否能够变成d中的元素 

 

   String longestWord = "";

    for (String target : d) {

        int l1 = longestWord.length(), l2 = target.length();

        if (l1 > l2 || (l1 == l2 && longestWord.compareTo(target) < 0)) {

longetWord.compareTo(target) 比较字典顺序

            continue;

        }

        if (isValid(s, target)) {

            longestWord = target;

        }

    }

    return longestWord;

}

第二部分 判断s能否成为target字符串 双指针

private boolean isValid(String s, String target) {

    int i = 0, j = 0;

    while (i < s.length() && j < target.length()) {

        if (s.charAt(i) == target.charAt(j)) {

            j++;

        }

        i++;

    }

    return j == target.length();

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值