热门搜索 :
考研考公
您的当前位置:首页正文

Single Number

来源:东饰资讯网
Paste_Image.png

按位亦或可求解,复杂度为O(n)

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result=""
        for i in range(len(nums)):
            result ^=nums[i]
        return result
        # nums.sort()
        # for i in range(1,len(nums)-1,2):
        #     if nums[i] != nums[i-1]:
        #         return nums[i]
        # return nums[-1]
Paste_Image.png

import string
class Solution(object):
    """
    :type beginWord: str
    :type endWord: str
    :type wordList: Set[str]
    :rtype: int
    """
    def diff(self,word1,word2):
        k=0
        for i in range(len(word1)):
            if word1[i] != word2[i]:
                k+=1
        if k==1:
            return True
    def ladderLength(self, beginWord, endWord, wordList):
        # if no need trse the tree
        if self.diff(beginWord,endWord):
            return 2
        #go trougth map
        queue = [beginWord]
        map = {beginWord:1}
        while len(queue) > 0:
            #get head num
            current = queue.pop(0)
            #get the deep tree
            headDist = map.get(current)

            for i in range(len(current)):
                for t in string.ascii_lowercase:
                    if current[i] == t:
                        continue
                    # replace a new word
                    tempStr = current[:i] + t + current[i+1:]
                    #get the result
                    if tempStr == endWord:
                        return headDist+1
                    if tempStr in wordList:
                        map[tempStr] = headDist+1
                        queue.append(tempStr)
                        wordList.remove(tempStr)
        return 0
Top