- (简单)给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
answer:
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = set(nums)
ma = 0
for i in l:
x = nums.count(i)
if x > ma:
ma = x
re = i
return re
- (简单)给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
answer
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
m = len(nums)
for i in range(m):
t = target - nums[i]
for j in range(m):
if i != j and t == nums[j]:
return i,j
3.(中等)给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
answer
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy_head = ListNode(-1)
cur = dummy_head
carry = 0
while l1 is not None and l2 is not None:
val = l1.val + l2.val + carry
cur.next = ListNode(val % 10)
cur = cur.next
carry = val // 10
l1 = l1.next
l2 = l2.next
while l1 is not None:
val = l1.val + carry
cur.next = ListNode(val % 10)
cur = cur.next
carry = val // 10
l1 = l1.next
while l2 is not None:
val = l2.val + carry
cur.next = ListNode(val % 10)
cur = cur.next
carry = val // 10
l2 = l2.next
if carry == 1:
cur.next = ListNode(1)
return dummy_head.next