Tag5 242. Valid Anagram 349. Intersection of Two Arrays 202. Happy Number 1. Two Sum

242. Valid Anagram([ˈænəˌgræm]回文构词)(valid 有效的)

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging(重新布置的) the letters of a different word or phrase, typically using all the original letters exactly once.

 1. ord("26 letters") - ord("a") in the range 0-25 , so we need a hashmap of size 26.then use [0]*26

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        record = [0] * 26

        for i in s:
            record[ord(i) - ord("a")] += 1 # thats why we only need a tablesize of size 26
        for i in t:
            record[ord(i) - ord("a")] -= 1 # wrong: ord[]

        for i in range(26):
            if record[i] != 0:
                return False
        return True #at the front position,not in the for loop
            

349. Intersection of Two Arrays

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

 Generally, a dictionary is used to make a hashmap. Here, an array is used to make a hashmap.

	
class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        count1 = [0]*1001
        count2 = [0]*1001
        result = []
        for i in range(len(nums1)):
            count1[nums1[i]]+=1
        for j in range(len(nums2)):
            count2[nums2[j]]+=1
        for k in range(1001):
            if count1[k]*count2[k]>0:
                result.append(k)
        return result

cheat solution:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        ls = []
        for i in nums1:
            if i in nums2:
                ls.append(i)
        return list(set(ls))

 super cheatsolution:

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return list(set(nums1) & set(nums2))

 202. Happy Number

Write an algorithm to determine if a number n is happy.

happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits(位数).
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle(无线循环) which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

class Solution:
    def isHappy(self, n: int) -> bool:
        ls = [] #make a map contains all the sum for each loop
        su = self.digitssum(n)

        while su not in ls:# important loop condition
            ls.append(su)
            su = self.digitssum(su)
            if su == 1:
                return True
        return False


    def digitssum(self,n):
        su = 0
        st = str(n)
        for i in st:
            su += int(i)**2
        return su

 Think about the meaning of each number in the hashmap and what the corresponding index represents.

another way to get sum of digits:

    def get_sum(self,n: int) -> int: 
        new_num = 0
        while n:
            n, r = divmod(n, 10) #quotient商, remainder余数 = divmod(n ,10 )
            new_num += r ** 2
        return new_num

 1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        dic = {}
        for i, num in enumerate(nums):
            val = target - num

            if val not in dic:
                dic[num] = i
            else:
                return[i,dic[val]]

remenber!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 

violence solution:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i,j]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值