- Add Binary
題目描述;
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
簡單描述:二進制相加
代碼如下:
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
print(bin(int(a,2)+int(b,2))[2:])
return bin(int(a,2)+int(b,2))[2:]
s=Solution()
s.addBinary("1010","1011")
python的函數真他孃的多。
本題中用到的:
bin() 返回一個整數 int 或者長整數 long int 的二進制表示。
示例如下:
>>>bin(10)
'0b1010'
>>> bin(20)
'0b10100'
上面的例子也說明了代碼中爲什麼用到了[2:],就是從第3位開始;
然後讓我們重新認識以下int這個函數:
int(x, base=10)
x -- 字符串或數字。
base -- 進制數,默認十進制。
舉例如下:
>>>int() # 不傳入參數時,得到結果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16) # 如果是帶參數base的話,12要以字符串的形式進行輸入,12 爲 16進制
18
>>> int('0xa',16)
10
>>> int('10',8)
8
69. Sqrt(x)
題目描述:
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
翻譯:求所給數字的平方根;
我做的第一種方法:
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
mid=x//2
if x == 0 or x == 1:
return x
for i in range(mid+1):
if i * i <= x and (i + 1) * (i + 1) > x:
print(i)
return i
這種方法在編譯器上可以AC,但是到了LeetCode的平臺就提示:
351 / 1017 test cases passed.
Status: Time Limit Exceeded
也就是說時間複雜度太大了,畢竟是一個一個遍歷。
第二種方法【二分思想】:
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
low,high=0,x
while low <= high:
mid = (low + high) / 2
if mid ** 2 <= x:
low = mid + 1
else:
high = mid - 1
return low - 1
s=Solution()
s.mySqrt(4)
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]
我的解法:
起初我是這樣寫的:
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.
"""
for i in range(len(nums2)):
nums1.append(nums2[i])
nums1.sort()
s=Solution()
s.merge([1,2,3,0,0,0],3,[2,5,6],3)
可是輸出有0沒法處理;
最後這樣寫的:
for i in range(len(nums2)):
nums1[i+m]=nums2[i]
nums1.sort()
還有一種寫法,值得學習,利用了堆棧的思維;
while(len(nums1)>m):
nums1.pop(m)
while(len(nums2)>n):
nums2.pop(n)
for i in nums2:
nums1.append(i)
nums1.sort()