LeetCode刷题之路 part 1 双指针

TOC

Part 1 双指针

167. Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.

AC代码(Python):

class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        for i in range(0,len(numbers)):
            if numbers[i] + numbers[i+1] == target:   #两个连续的值相和等于目标值
                return [i+1,i+2]
            if i!=0 and numbers[i] == numbers[i-1]:  #若指针i扫描到相同值增跳过
                continue
            for j in range(i+1,len(numbers)):
                if j != 0 and numbers[j] == numbers[j - 1]:  #若指针j扫描到相同值增跳过
                    continue
                if numbers[i] + numbers[j] == target:
                    return [i+1,j+1]

633. Sum of Square Numbers

Given a non-negative integer c, your task is to decide whether there’re two integers a and b such that a2 + b2 = c.
Example 1:
Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5
Example 2:
Input: 3
Output: False

AC代码(Python):

class Solution:
    def judgeSquareSum(self, c):
        """
        :type c: int
        :rtype: bool
        """
        import math
        if c==1 or c==0:
            return True
        for j in range(1,c):
            if j*j >c:
                return False
            tmp =math.sqrt(c - (j*j))
            if tmp == int(tmp):
                return True
        return False

345. Reverse Vowels of a String

Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: “hello”
Output: “holle”
Example 2:
Input: “leetcode”
Output: “leotcede”
Note:
The vowels does not include the letter “y”.

AC代码(Python):

class Solution:
    def reverseVowels(self, s):
        """
        :type s: str
        :rtype: str
        """
        vowel = {"a":"in","e":"in","i":"in","o":"in","u":"in","A":"in","E":"in","I":"in","O":"in","U":"in"}
        s = list(s)

        i = 0
        j = len(s)-1
        while i<j:
            if s[i] not in vowel.keys() :
                i += 1
                continue
            if s[j] not in vowel.keys() :
                j -= 1
                continue
            s[i],s[j] = s[j],s[i]
            i += 1
            j -= 1

        s = "".join(s)
        return s

88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output:
[1,2,2,3,5,6]

AC代码(Python):

class Solution:
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: void Do not return anything, modify nums1 in-place instead.
        """
        nums1[m:m+n] = nums2
        nums1.sort()

141. Linked List Cycle

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 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?

AC代码(Python):

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:  # 判断无节点或者单节点的情况
            return False
        slow = head
        fast = head
        while fast.next  and fast.next.next :  #判断走的快的指针是否还有路可走

            slow = slow.next  #慢指针走一步
            fast = fast.next.next #快指针走两步
            if slow == fast:  #一定要先走,再判断是否两人相遇
                return True

        return False

524. Longest Word in Dictionary through Deleting

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input:
s = “abpcplea”, d = [“ale”,“apple”,“monkey”,“plea”]
Output:
“apple”
Example 2:
Input:
s = “abpcplea”, d = [“a”,“b”,“c”]
Output:
“a”
Note:
All the strings in the input will only contain lower-case letters.
The size of the dictionary won’t exceed 1,000.
The length of all the strings in the input won’t exceed 1,000.

AC代码(Python):

import functools
class Solution(object):
    def findLongestWord(self, s, d):
        """
        :type s: str
        :type d: List[str]
        :rtype: str
        """
        ans = []
        for i in range(len(d)):
            cur = d[i]
            tmp =s
            for j in range(len(cur)):
                num = tmp.find(cur[j])           
                if num == -1 :
                    break
                tmp = tmp[num+1:]             
                if j == len(cur) -1:
                   ans.append([cur,len(cur)])

        if ans == []:
            return ""
        ans = sorted(ans, key=functools.cmp_to_key(self.cmp))
        return ans[0][0]

    def cmp(self, a, b):
        if a[1] > b[1]:
            return -1
        if a[1] < b[1]:
            return  1
        if a[0] < b[0]:
            return -1
        if a[0] > b[0]:
            return  1
        return 0
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值