LeetCode Hash Table算法题(Easy级别)整理 Part 2

136. Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

解题思路:利用异或运算,对应位上相同,异或结果为0;否则,为1。

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = nums[0]
        for n in nums[1:]:
            ans ^= n
        return ans

389. Find the Difference

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

解题思路:同136. Single Number。

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        if not s:
            return t
        ans = ord(s[0])
        for c in s[1:]:
            ans ^= ord(c)
        for c in t:
            ans ^= ord(c)
        return chr(ans)

387. First Unique Character in a String

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

解题思路:利用字母表,对每个字母进行判断。

class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        index = len(s)
        alphabet = "abcdefghijklmnopqrstuvwxyz"
        for i in alphabet:
            x = s.find(i)
            if x != -1:
                y = s.rfind(i)
                if x == y:
                    if x < index:
                        index = x
        if index != len(s):
            return index
        return -1

点赞