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()
Tuesday, November 28, 2017
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:]
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
# 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
# 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
# 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
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)
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
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)
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
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
451. Sort Characters By Frequency
class Solution:
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
a_dict = {}
b_dict = {}
new_string = ""
new_list = []
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = 1
else:
a_dict[s[i]] += 1
for (keys, values) in a_dict.items():
if values not in b_dict:
b_dict[values] = keys * values
else:
b_dict[values] = b_dict[values] + keys * values
new_list = sorted(list(b_dict.keys()))
for j in new_list:
new_string = b_dict[j] + new_string
return new_string
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
a_dict = {}
b_dict = {}
new_string = ""
new_list = []
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = 1
else:
a_dict[s[i]] += 1
for (keys, values) in a_dict.items():
if values not in b_dict:
b_dict[values] = keys * values
else:
b_dict[values] = b_dict[values] + keys * values
new_list = sorted(list(b_dict.keys()))
for j in new_list:
new_string = b_dict[j] + new_string
return new_string
Tuesday, November 21, 2017
412. Fizz Buzz
class Solution:
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
new_list = []
for i in range(n):
if (i+1) % 15 == 0:
new_list.append("FizzBuzz")
elif (i+1) % 3 == 0:
new_list.append("Fizz")
elif (i+1) % 5 == 0:
new_list.append("Buzz")
else:
new_list.append(str(i+1))
return new_list
def fizzBuzz(self, n):
"""
:type n: int
:rtype: List[str]
"""
new_list = []
for i in range(n):
if (i+1) % 15 == 0:
new_list.append("FizzBuzz")
elif (i+1) % 3 == 0:
new_list.append("Fizz")
elif (i+1) % 5 == 0:
new_list.append("Buzz")
else:
new_list.append(str(i+1))
return new_list
537. Complex Number Multiplication
class Solution:
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_list = a.split("+")
b_list = b.split("+")
first_part = int(a_list[0])*int(b_list[0]) + int(a_list[1][:-1])*int(b_list[1][:-1])*(-1)
second_part = str(int(a_list[0])*int(b_list[1][:-1]) + int(b_list[0])*int(a_list[1][:-1]))+"i"
return str(first_part)+"+"+second_part
def complexNumberMultiply(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
a_list = a.split("+")
b_list = b.split("+")
first_part = int(a_list[0])*int(b_list[0]) + int(a_list[1][:-1])*int(b_list[1][:-1])*(-1)
second_part = str(int(a_list[0])*int(b_list[1][:-1]) + int(b_list[0])*int(a_list[1][:-1]))+"i"
return str(first_part)+"+"+second_part
Sunday, November 19, 2017
728. Self Dividing Numbers
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
new_list = []
def is_self_dividing (number):
for i in list(str(number)):
if int(i) == 0:
return False
elif number % int(i)!=0:
return False
return True
for number in range(left, right+1):
if is_self_dividing (number) == True:
new_list.append(number)
return new_list
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
new_list = []
def is_self_dividing (number):
for i in list(str(number)):
if int(i) == 0:
return False
elif number % int(i)!=0:
return False
return True
for number in range(left, right+1):
if is_self_dividing (number) == True:
new_list.append(number)
return new_list
387. First Unique Character in a String
class Solution:
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
b_dict = {}
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = i
else:
a_dict[s[i]] = -1
for (a_key, a_value) in a_dict.items():
if a_dict[a_key] != -1:
b_dict[a_key] = a_value
if b_dict == {}:
return -1
else:
return min(b_dict.values())
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
b_dict = {}
for i in range(len(s)):
if s[i] not in a_dict:
a_dict[s[i]] = i
else:
a_dict[s[i]] = -1
for (a_key, a_value) in a_dict.items():
if a_dict[a_key] != -1:
b_dict[a_key] = a_value
if b_dict == {}:
return -1
else:
return min(b_dict.values())
Saturday, November 18, 2017
405. Convert a Number to Hexadecimal
class Solution:
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
digits = "0123456789abcdef"
temp = ""
number = num
if number == 0:
return "0"
elif number < 0:
number += 0x100000000
while number >0:
remain = number % 16
number = number //16
temp += digits[remain]
return temp[::-1]
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
digits = "0123456789abcdef"
temp = ""
number = num
if number == 0:
return "0"
elif number < 0:
number += 0x100000000
while number >0:
remain = number % 16
number = number //16
temp += digits[remain]
return temp[::-1]
461. Hamming Distance
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
693. Binary Number with Alternating Bits
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bits = bin(n)
for i in range(len(bits)-1):
if bits[i] == bits[i+1]:
return False
return True
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bits = bin(n)
for i in range(len(bits)-1):
if bits[i] == bits[i+1]:
return False
return True
155. Min Stack
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1=[]
self.stack2=[]
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack1.append(x)
if len(self.stack2) == 0 or x <= self.stack2[-1]:
self.stack2.append(x)
def pop(self):
"""
:rtype: void
"""
top = self.stack1[-1]
self.stack1.pop()
if top == self.stack2[-1]:
self.stack2.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1=[]
self.stack2=[]
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack1.append(x)
if len(self.stack2) == 0 or x <= self.stack2[-1]:
self.stack2.append(x)
def pop(self):
"""
:rtype: void
"""
top = self.stack1[-1]
self.stack1.pop()
if top == self.stack2[-1]:
self.stack2.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
Friday, November 17, 2017
345. Reverse Vowels of a String
class Solution:
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
string_copy = s
vowels = "aeiouAEIOU"
vowel_string=""
new_string=""
for i in string_copy:
if i in vowels:
vowel_string+=i
print (vowel_string)
reverse_vowel_string = vowel_string[::-1]
print (reverse_vowel_string)
j = 0
for i in string_copy:
if i in vowels:
new_string += reverse_vowel_string[j]
j+=1
else:
new_string +=i
return new_string
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
string_copy = s
vowels = "aeiouAEIOU"
vowel_string=""
new_string=""
for i in string_copy:
if i in vowels:
vowel_string+=i
print (vowel_string)
reverse_vowel_string = vowel_string[::-1]
print (reverse_vowel_string)
j = 0
for i in string_copy:
if i in vowels:
new_string += reverse_vowel_string[j]
j+=1
else:
new_string +=i
return new_string
599. Minimum Index Sum of Two Lists
class Solution:
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
list1_dict ={}
dict_2={}
for i in range(len(list1)):
list1_dict[list1[i]] = i
for j in range(len(list2)):
if list2[j] in list1_dict:
add_index = j+list1_dict[list2[j]]
if add_index not in dict_2:
dict_2[add_index]=[]
dict_2[add_index].append(list2[j])
else:
dict_2[add_index].append(list2[j])
return dict_2[min(dict_2.keys())]
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
list1_dict ={}
dict_2={}
for i in range(len(list1)):
list1_dict[list1[i]] = i
for j in range(len(list2)):
if list2[j] in list1_dict:
add_index = j+list1_dict[list2[j]]
if add_index not in dict_2:
dict_2[add_index]=[]
dict_2[add_index].append(list2[j])
else:
dict_2[add_index].append(list2[j])
return dict_2[min(dict_2.keys())]
Thursday, November 16, 2017
520. Detect Capital
class Solution:
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if word == "":
return False
elif word.isupper():
return True
elif word.islower():
return True
elif word[0].isupper():
if word[1:].islower():
return True
else:
return False
else:
return False
def detectCapitalUse(self, word):
"""
:type word: str
:rtype: bool
"""
if word == "":
return False
elif word.isupper():
return True
elif word.islower():
return True
elif word[0].isupper():
if word[1:].islower():
return True
else:
return False
else:
return False
485. Max Consecutive Ones
class Solution:
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.append(0)
count = 0
max_count = 0
for i in nums:
if i == 1:
count += 1
elif i == 0:
if max_count < count:
max_count = count
count = 0
return max_count
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.append(0)
count = 0
max_count = 0
for i in nums:
if i == 1:
count += 1
elif i == 0:
if max_count < count:
max_count = count
count = 0
return max_count
219. Contains Duplicate II
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
a_dict={}
for i in range(len(nums)):
if nums[i] not in a_dict:
a_dict[nums[i]] = i
else:
if i - a_dict[nums[i]] <= k:
return True
else:
a_dict[nums[i]] = i
return False
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
a_dict={}
for i in range(len(nums)):
if nums[i] not in a_dict:
a_dict[nums[i]] = i
else:
if i - a_dict[nums[i]] <= k:
return True
else:
a_dict[nums[i]] = i
return False
28. Implement strStr()
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
Sunday, November 12, 2017
20. Valid Parentheses
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
new_string = ""
left = "({["
right = ")}]"
for i in s:
if i in left:
new_string += i
elif i in right:
if len(new_string) == 0:
return False
if right.index(i)!=left.index(new_string[-1]):
return False
else:
new_string = new_string[:-1]
return len(new_string) == 0
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
new_string = ""
left = "({["
right = ")}]"
for i in s:
if i in left:
new_string += i
elif i in right:
if len(new_string) == 0:
return False
if right.index(i)!=left.index(new_string[-1]):
return False
else:
new_string = new_string[:-1]
return len(new_string) == 0
Monday, November 6, 2017
441. Arranging Coins
class Solution:
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
i=1
new_number = n
while new_number >= 0:
new_number = new_number-i
i += 1
return i-2
optimized version:
import math
class Solution:
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
return int(math.sqrt(2 * n + 0.25) - 0.5)
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
i=1
new_number = n
while new_number >= 0:
new_number = new_number-i
i += 1
return i-2
optimized version:
import math
class Solution:
def arrangeCoins(self, n):
"""
:type n: int
:rtype: int
"""
return int(math.sqrt(2 * n + 0.25) - 0.5)
242. Valid Anagram
class Solution:
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def construct_dict(a_string):
a_dict={}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
if dict_1 == dict_2:
return True
else:
return False
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
def construct_dict(a_string):
a_dict={}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
if dict_1 == dict_2:
return True
else:
return False
58. Length of Last Word
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
new_string = s
new_string = new_string.lower()
new_list = new_string.split()
try:
return len(new_list[-1])
except:
return 0
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
new_string = s
new_string = new_string.lower()
new_list = new_string.split()
try:
return len(new_list[-1])
except:
return 0
Sunday, November 5, 2017
7. Reverse Integer
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
value = 0
if x >= 2147483647 or x <= -2147483647:
return 0
try:
if x > 0:
value = int(str(x)[::-1])
elif x < 0:
value = -int(str(-x)[::-1])
if value >= 2147483647 or value <= -2147483647:
return 0
return value
except OverflowError:
return 0
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
value = 0
if x >= 2147483647 or x <= -2147483647:
return 0
try:
if x > 0:
value = int(str(x)[::-1])
elif x < 0:
value = -int(str(-x)[::-1])
if value >= 2147483647 or value <= -2147483647:
return 0
return value
except OverflowError:
return 0
125. Valid Palindrome
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if s == "":
return True
else:
new_string = s
new_string = new_string.lower()
new_list = []
for i in new_string:
if (ord(i) >= 97 and ord(i) <= 122) or (ord(i) >= 48 and ord(i) <= 57):
new_list.append(i)
new_string = ("").join(new_list)
print (new_string)
if new_string == new_string[::-1]:
return True
else:
return False
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
if s == "":
return True
else:
new_string = s
new_string = new_string.lower()
new_list = []
for i in new_string:
if (ord(i) >= 97 and ord(i) <= 122) or (ord(i) >= 48 and ord(i) <= 57):
new_list.append(i)
new_string = ("").join(new_list)
print (new_string)
if new_string == new_string[::-1]:
return True
else:
return False
290. Word Pattern
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
a_dict = {}
new_list = str.split()
if len(pattern) != len(new_list):
return False
else:
for i in range(len(pattern)):
if pattern[i] in a_dict:
if a_dict[pattern[i]] != new_list[i]:
return False
else:
if new_list[i] in a_dict.values():
return False
else:
a_dict[pattern[i]] = new_list[i]
return True
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
a_dict = {}
new_list = str.split()
if len(pattern) != len(new_list):
return False
else:
for i in range(len(pattern)):
if pattern[i] in a_dict:
if a_dict[pattern[i]] != new_list[i]:
return False
else:
if new_list[i] in a_dict.values():
return False
else:
a_dict[pattern[i]] = new_list[i]
return True
205. Isomorphic Strings
class Solution:
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
a_dict = {}
if len(s) != len(t):
return False
else:
for i in range(len(s)):
if s[i] in a_dict:
if a_dict[s[i]] != t[i]:
return False
else:
if t[i] in a_dict.values():
return False
else:
a_dict[s[i]] = t[i]
return True
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
a_dict = {}
if len(s) != len(t):
return False
else:
for i in range(len(s)):
if s[i] in a_dict:
if a_dict[s[i]] != t[i]:
return False
else:
if t[i] in a_dict.values():
return False
else:
a_dict[s[i]] = t[i]
return True
Saturday, November 4, 2017
434. Number of Segments in a String
class Solution:
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
new_list = []
new_list = s.split()
return len(new_list)
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
new_list = []
new_list = s.split()
return len(new_list)
35. Search Insert Position
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums[-1] < target:
return len(nums)
elif nums[0] >= target:
return 0
else:
start_index = 0
end_index = len(nums)-1
while start_index + 1 <= end_index:
middle_index = (start_index + end_index +1)//2
if start_index + 1 == end_index:
return end_index
else:
if nums[middle_index] == target:
return middle_index
elif nums[middle_index] < target:
start_index = middle_index
else:
end_index = middle_index
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if nums[-1] < target:
return len(nums)
elif nums[0] >= target:
return 0
else:
start_index = 0
end_index = len(nums)-1
while start_index + 1 <= end_index:
middle_index = (start_index + end_index +1)//2
if start_index + 1 == end_index:
return end_index
else:
if nums[middle_index] == target:
return middle_index
elif nums[middle_index] < target:
start_index = middle_index
else:
end_index = middle_index
217. Contains Duplicate
class Solution:
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
result = False
a_dict = {}
for i in range(len(nums)):
if nums[i] in a_dict:
result = True
break
else:
a_dict[nums[i]] = 1
return result
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
result = False
a_dict = {}
for i in range(len(nums)):
if nums[i] in a_dict:
result = True
break
else:
a_dict[nums[i]] = 1
return result
389. Find the Difference
class Solution:
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
def construct_dict(a_string):
a_dict = {}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
for a_key in dict_2.keys():
try:
dict_1[a_key]
except KeyError:
return a_key
else:
if dict_1 [a_key] != dict_2 [a_key]:
return a_key
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
def construct_dict(a_string):
a_dict = {}
for i in range(len(a_string)):
if a_string[i] in a_dict:
a_dict[a_string[i]] += 1
else:
a_dict[a_string[i]] = 1
return a_dict
dict_1 = construct_dict(s)
dict_2 = construct_dict(t)
for a_key in dict_2.keys():
try:
dict_1[a_key]
except KeyError:
return a_key
else:
if dict_1 [a_key] != dict_2 [a_key]:
return a_key
409. Longest Palindrome
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
for i in range (len(s)):
if s[i] in a_dict:
a_dict[s[i]] += 1
else:
a_dict[s[i]] = 1
count = 0
unit = 0
for a_value in a_dict.values():
if a_value % 2 == 0:
count += a_value
else:
count += (a_value//2)*2
unit = 1
return count + unit
def longestPalindrome(self, s):
"""
:type s: str
:rtype: int
"""
a_dict = {}
for i in range (len(s)):
if s[i] in a_dict:
a_dict[s[i]] += 1
else:
a_dict[s[i]] = 1
count = 0
unit = 0
for a_value in a_dict.values():
if a_value % 2 == 0:
count += a_value
else:
count += (a_value//2)*2
unit = 1
return count + unit
Friday, November 3, 2017
557. Reverse Words in a String III
class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
new_list = []
new_list = s.split()
new_string=""
for i in range(0,len(new_list)):
new_list[i] = new_list[i][::-1]
new_string = " ".join(new_list)
return new_string
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
new_list = []
new_list = s.split()
new_string=""
for i in range(0,len(new_list)):
new_list[i] = new_list[i][::-1]
new_string = " ".join(new_list)
return new_string
Thursday, November 2, 2017
344. Reverse String
class Solution:
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
def reverseString(self, s):
"""
:type s: str
:rtype: str
"""
return s[::-1]
9. Palindrome Number
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x == int(str(x)[::-1]):
return True
else:
return False
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x == int(str(x)[::-1]):
return True
else:
return False
Subscribe to:
Comments (Atom)