Given an array of size n, find the majority element. The majority element is the element that appears more than⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
解: 逐步檢查: 誰一超過一半 就馬上輸出
這樣也滿快的
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m=len(nums)
l={}
for i in nums:
if i in l:
l[i]+=1
else:
l[i]=1
if l[i]>m//2:
MOore 投票法:
速度上更快一些 O(n) linear time and O(1) space
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count=1
num=nums[0]
for i in nums:
if i==num:
count+=1
if i!=num:
count=count-1
if count==0:
num=i
count=1
return num
return i
You're given stringsJrepresenting the types of stones that are jewels, andSrepresenting the stones you have. Each character inSis a type of stone you have. You want to know how many of the stones you have are also jewels.
The letters inJare guaranteed distinct, and all characters inJandSare letters. Letters are case sensitive, so"a"is considered a different type of stone from"A".
Example 1:
Input: J = "aA", S = "aAAbbbb"
Output: 3
Example 2:
Input: J = "z", S = "ZZ"
Output: 0
Note:
SandJwill consist of letters and have length at most 50.
The characters inJare distinct.
解法:
class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ count=0 for i in S: if i in J: count+=1 return count
1365.How Many Numbers Are Smaller Than the Current Number
Easy
Given the arraynums, for eachnums[i]find out how many numbers in the array are smaller than it. That is, for eachnums[i]you have to count the number of validj's such that j != iandnums[j] < nums[i].
Return the answer in an array.
Example 1:
Input: nums = [8,1,2,2,3]
Output: [4,0,1,1,3]
Explanation:
For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
For nums[1]=1 does not exist any smaller number than it.
For nums[2]=2 there exist one smaller number than it (1).
For nums[3]=2 there exist one smaller number than it (1).
For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).