Python题库积累
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组[1,2,3,2,2,2,5,4,2]。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。
def MoreThanHalfNum_Solution(numbers): d={} for i in numbers: if i in d: d[i]+=1 else: d[i]=1 print(d) for j in d: if d[j]>len(numbers)/2: return j A = MoreThanHalfNum_Solution([1, 2, 3, 2, 2, 2, 5, 4, 2]) print(A)
找出字符串中出现的第一个不重复的字符。
#利用字符串内置的count函数,遍历字符串时,遇到count为1时,返回。
def findFirstCharacter(pstr): for i in range(len(pstr)): if pstr.count(pstr[i])==1: #count() 方法用于统计字符串里某个字符出现的次数 return pstr[i] return None firstChar = findFirstCharacter("abcabcfghkkk") print(firstChar) 输出结果:f
给定一个整数数组 nums
和一个目标值 target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
【示例】
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
class Solution(object): def twoSum(self, nums,target): for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i]+nums[j]==target: return [i,j] if __name__=="__main__": S = Solution() nums = [1,2,5,7] target = 7 print(S.twoSum(nums,target))
输出结果:[1,2]