代碼隨想錄算法訓練營第六天| 242.有效的字母異位詞 349. 兩個數(shù)組的交集 202. 快樂數(shù) 1. 兩數(shù)之和

什么時候想到用哈希法,當我們遇到了要快速判斷一個元素是否出現(xiàn)集合里的時候,就要考慮哈希法!!順便再次回顧一下二分搜索和雙指針,二分搜索通常用于已經(jīng)安好順序的數(shù)組,并且并且不能重復(fù)出現(xiàn),其時間復(fù)雜度為 nlogn,雙指針主要用于去找到指定的符合條件的subarray。

242.有效的字母異位詞.

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 自己看到題目的第一想法?

簡單的anagram題目,用hash map即可。

#2 看完代碼隨想錄之后的想法??

題目basically就是看t是不是出現(xiàn)了s中的所有的characters。經(jīng)典的hash table的使用場景。

#3 類似題目?

383和242是幾乎完全一樣的題目,為了練習,此題使用了map,而242使用了object。

49比較簡單,438其實是之前的雙指針做過的題目,是雙指針和hashmap的結(jié)合。

349. 兩個數(shù)組的交集? ??

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.

#1 自己看到題目的第一想法?

兩個set即可解決。

順便復(fù)習一下語法,set用has來看是否出現(xiàn)過某值,string中是否出現(xiàn)過某個substring用includes()。

202. 快樂數(shù)??

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

A?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.

#1 自己看到題目的第一想法?

就使用while循環(huán),直到結(jié)果等于1或者是結(jié)果已經(jīng)出現(xiàn)過了(set.size不變) 。

#2 看完代碼隨想錄之后的想法? ??

關(guān)于求一個數(shù)字的個個位數(shù)的和:

const getSum=(num)=>{

? ? ? ? ? ? ? ? let sum=0

? ? ? ? ? ? ? ? while(n) {?

? ? ? ? ? ? ? ? ????sum+=(n%10)

? ? ? ? ? ? ? ? ? ? n=Math.floor(n/10)

? ? ? }

return sum }

#3 收獲??

對set的操作更加熟悉,set.add(), set.has(), set.size? ? ??

1. 兩數(shù)之和??

Given an array of integers?numsand 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.

#1 自己看到題目的第一想法? ? ? ? ? ? ? ? ? ? ? ? ? ?

快速判斷是否有某值(target - arr[i]) 出現(xiàn),就可以考慮用哈希了,

#2 看完代碼隨想錄之后的想法? ???

為什么會想到用哈希表:#1中解釋過了

哈希表為什么用map:?因為需要key和value(用來記錄下標)

本題map是用來存什么的: target - arr[i]

map中的key和value用來存什么的:value存?arr[i] 的下標?

#3 收獲? ? ??

使用數(shù)組和set來做哈希法的局限。

數(shù)組的大小是受限制的,而且如果元素很少,而哈希值太大會造成內(nèi)存空間的浪費。

set是一個集合,里面放的元素只能是一個key,而兩數(shù)之和這道題目,不僅要判斷y是否存在而且還要記錄y的下標位置,因為要返回x 和 y的下標。所以set 也不能用。

此時就要選擇另一種數(shù)據(jù)結(jié)構(gòu):map ,map是一種key value的存儲結(jié)構(gòu),可以用key保存數(shù)值,用value在保存數(shù)值所在的下標。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容