Sunday, December 17, 2017

69. Sqrt(x)

Newton method:

class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        xi = x
        while xi*xi > x:
            xi = int((xi+x/xi)/2)
        return xi

Sunday, December 10, 2017

162. Find Peak Element

class Solution:
    def findPeakElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        left,right = 0, len(nums)-1
        while left < right:
            mid = (left + right)//2
            if nums[mid] < nums[mid+1]:
                left = mid+1
            else:
                right = mid
        return left

500. Keyboard Row

class Solution(object):
    def findWords(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        keyboard= ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
        new_list=[]
        for a_word in words:
            lower_a_word = a_word.lower()
            for line in keyboard:
                if set(lower_a_word).issubset(set(line)):
                    new_list.append(a_word)
        return new_list
best solution


class Solution(object):
    def findWords(self, words):
        line1, line2, line3 = set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')
        ret = []
        for word in words:
            w = set(word.lower())
            if w.issubset(line1) or w.issubset(line2) or w.issubset(line3):
                ret.append(word)
        return ret

561. Array Partition I

class Solution:
    def arrayPairSum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        new_array = sorted(nums)
        return sum(new_array[::2])

Thursday, December 7, 2017

78. Subsets

from itertools import combinations
class Solution:
    def subsets(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        k = 0
        new_list= []
        while k < len(nums)+1:
            for c in combinations(nums, k):
                new_list.append(list(c))
            k +=1
        return new_list

541. Reverse String II

class Solution:
    def reverseStr(self, s, k):
        """
        :type s: str
        :type k: int
        :rtype: str
        """
        new_list = list(s)
        i = 0
        while i< len(s):
            if i+k > len(s):
                new_list[i:] = new_list[i:][::-1]
            else:
                new_list[i:i+k] = new_list[i:i+k][::-1]
            i = i+k*2
        return ''.join(new_list)

Sunday, December 3, 2017

414. Third Maximum Number

class Solution:
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        new_list = list(set(nums))
        sorted_new_list = sorted(new_list)
        try:
            return sorted_new_list[-3]
        except:
            return sorted_new_list[-1]

class Solution:
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        a = b = c = float("-inf")
        for n in nums:
            if n > a:
                a, b, c = n, a, b
            elif a > n > b:
                b, c =n, b
            elif b > n > c:
                c = n
        return c if c != float("-inf") else a

Saturday, December 2, 2017

349. Intersection of Two Arrays

class Solution:
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list(set(nums1)&set(nums2))

347. Top K Frequent Elements

from collections import Counter
class Solution:
    def topKFrequent(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: List[int]
        """
        counts = Counter(nums)
        k_frequent = counts.most_common(k)
        return [x[0] for x in k_frequent]

258. Add Digits

class Solution:
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        if num == 0:
            return 0
        else:
            return 1 + (num - 1) % 9

Tuesday, November 28, 2017

215. Kth Largest Element in an Array

import heapq
class Solution:
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        new_list = heapq.nlargest(k,nums)
        return new_list.pop()

Saturday, November 25, 2017

67. Add Binary

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        return bin(int(a, 2)+int(b,2))[2:]

83. Remove Duplicates from Sorted List

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

class Solution:
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(None)
        dummy.next = head
        previous = dummy
        current = head
        while current:
            if current.val == previous.val:
                previous.next = current.next
            else:
                previous = current
            current = current.next
        return dummy.next

203. Remove Linked List Elements

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

class Solution:
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        dummy = ListNode(0)
        previous = dummy
        dummy.next = head
        current = head
        while current:
            if current.val == val:
                previous.next = current.next
            else:
                previous = current
            current = current.next
        return dummy.next

237. Delete Node in a Linked List

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

class Solution(object):
    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        node.val = node.next.val
        node.next = node.next.next

231. Power of Two

class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if bin(n)[2] == "1" and bin(n)[3:] == (len(bin(n))-3) * "0":
            return True
        else:
            return False

504. Base 7

class Solution:
    def convertToBase7(self, num):
        """
        :type num: int
        :rtype: str
        """
        divider = num
        def calculation (divider):
            number = ""
            while divider > 0:
                remainder = divider % 7
                divider = divider // 7
                number =str(remainder) + number
            return number
        if divider == 0:
            return "0"
        if divider < 0:
            return "-" + calculation (-divider)
        if divider > 0:
            return calculation (divider)

476. Number Complement

class Solution:
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        return int((len(bin(num))-2)*"1", 2)^num

Wednesday, November 22, 2017

682. Baseball Game

class Solution:
    def calPoints(self, ops):
        """
        :type ops: List[str]
        :rtype: int
        """
        new_list = []
        for i in range(len(ops)):
            if ops[i] == "C":
                new_list.pop()
            elif ops[i] == "D":
                new_list.append(int(new_list[-1])*2)
            elif ops[i] == "+":
                new_list.append(int(new_list[-1])+int(new_list[-2]))
            else:
                new_list.append(int(ops[i]))
        return sum(new_list)

657. Judge Route Circle

class Solution:
    def judgeCircle(self, moves):
        """
        :type moves: str
        :rtype: bool
        """
        num1 = 0
        num2 = 0
        for i in moves:
            if i == "R":
                num1 += 1
            if i == "L":
                num1 -= 1
            if i == "U":
                num2 += 1
            if i == "D":
                num2 -= 1
        if num1 == 0 and num2 ==0:
            return True
        else:
            return False