leetcode刷题记录13-14

介绍13

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

思路13

先排序再比较

代码13

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
t=False
nums.sort()
for i in range(len(nums)-1):
if nums[i]==nums[i+1]:
t=True
break
return t

介绍14

Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.

Note that it is the kth smallest element in the sorted order, not the kth distinct element.

Example:

1
2
3
4
5
6
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,

return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.

思路14

。。。有点无语,列表解析再排序就可以了,简单粗暴

代码14

1
2
3
4
5
6
7
8
9
10
class Solution(object):
def kthSmallest(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
new=[j for i in matrix for j in i]
new.sort()
return new[k-1]