36、数组中出现次数超过一半的数字
只会最笨的用字典遍历计数,然后判断value是否大于长度的一半。看了下别人的方法,参考思路来自博客:https://www.cnblogs.com/python27/archive/2011/12/15/2289534.html
自己用python实现。
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if not numbers:
return 0
else:
cur = [numbers[0], 1]
for i in numbers[1:]:
if i == cur[0]:
cur[1] += 1
else:
if cur[1] > 1:
cur[1] -= 1
elif cur[1] == 1:
cur = [i, 1]
print(cur)
return cur[0] if numbers.count(cur[0])>len(numbers)/2 else 0
37、整数中1出现的次数
多试几个数字就能找到规律了。虽然我也试了很久。写的比较长,但逻辑应该没有什么错误,可能可以在代码上进行改进。
# -*- coding:utf-8 -*-
class Solution:
def NumberOf1Between1AndN_Solution(self, n):
temp = str(n)
nums = [int(x) for x in list(temp)[::-1]]
count = 0
for i, num in enumerate(nums[:-1]):
pos = 10**i
pre = int(temp[:-(i+1)])
if num >= 1:
count += pos
count += pos*pre
if num < 1:
count += pos*pre
if nums[-1] > 1:
count += 10**(len(temp)-1)
else:
count += int(temp[1:])+1
return count
38、把数组排成最小的数
不会做,看了别人的思路。自己写了一遍冒泡排序的过程。等看了排序相关内容再重新用快排写一遍
class Solution:
def PrintMinNumber(self, numbers):
def swap(i, j):
numbers[i], numbers[j] = numbers[j], numbers[i]
def sortbynumadd(numbers):
flag = True
i = len(numbers)
while i > 0 and flag:
flag = False
for j in range(i-1):
if int(str(numbers[j]) + str(numbers[j+1])) > int(str(numbers[j+1]) + str(numbers[j])):
swap(j, j+1)
flag = True
i -= 1
return numbers
rst = sortbynumadd(numbers)
return ''.join([str(x) for x in rst])
39、数组中重复的数字
简单的直接用字典,时间空间复杂度都是O(n)。参考了别人的思路,时间复杂度O(n)空间复杂度O(1)
class Solution:
def duplicate(self, numbers, duplication):
long = len(numbers)
for i in range(len(numbers)):
index = numbers[i]%long if numbers[i] >= long else numbers[i]
if numbers[index] > long:
duplication[0] = index
return True
numbers[index] += long
return False
40、构造乘积数组
还是不会做。。参考https://www.nowcoder.com/questionTerminal/94a4d381a68b47b7a8bed86f2975db46
的第一条评论
class Solution:
def multiply(self, A):
B = [1]
for i in range(len(A)-1):
B.append(B[i]*A[i])
temp = 1
pos = -2
for j in range(len(A)-1, 0, -1):
temp *= A[j]
B[pos] *= temp
pos -= 1
return B
感觉今天的五道题大部分都不会做。还需要继续努力