貢獻者: 吸鎖-seesaw
A:interviewee
B:interviewer
A:我們這邊有一道題目,會給你一個integer的零陣列nums,每個元素會出現兩次除了一個數字只出現一次,請你找到只出現一次的數字。
A:array的長度介在1到30000間,整數的值介在負三萬到三萬間
B:所以我會拿到ㄧ個input 大小介在一到三萬的整數陣列,裡面每個值都介在正負三萬並且包含0,裡頭所有的值都會出現兩次,然後要把只有出現一次的
那個值印出來。
A:對的
B:好的,那我最直觀的想法應該會是用兩層for迴圈去做,將array裡的每一項去和整個array去比對一次,然後。
A:聽起來沒什麼問題,那我們就開始coding吧
可以用兩層for迴圈去將每一項和整個array比對一遍,將只有出現過一次的數字印出來。
A:這個方法在時間複雜度會是,有沒有辦可以降低他時間複雜度的方法。
B:如果用hash map的方法去嘗試,應該可以降低他的時間複雜度。
B:會做兩次的for迴圈,第一個for迴圈會去將給的nums 的array值去做mapping,接下來第二個for迴圈去讀取key的值,再把key值為一的印出來。
A:那我們開始coding吧
剛剛的所說的方法時間複雜度會是,如果要讓他的時間複雜度降低的話,可以用 hash map的方法,整體架構大概是兩個for迴圈,第一圈for迴圈用一個新的MAP array去紀錄出現次數,第二個for迴圈再去把MAP array等於1的值印出來。
A:這個做法的時間複雜度降低了,但空間複雜上升了,有沒有辦法去優化它的空間複雜度嗎
B:也許可以用Bitwise operation去嘗試,我們可以試著用XOR operation,我們知道XOR具有交換性,a ^ b ^ a=(a ^ a)^ b=且 a^a=0,即可找出single number。
A:interviewee
B:interviewer
A:So here is a int number n starting with a positive number, and replace it by the sum of the squares of its digits.Repeat the process until the number equals 1 which is a happy number,or loops endlessly in a cycle which does not include 1,which is not a happy number.
B:So i have to check whether if it's sum of the squared digits equals to 1 or not and kept repeating it .
A:You're right.
B:So I'll take 2 as an example
2 -> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20
-> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20
-> 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20
so it repeats after doing some ditgit squared sum .
I will approach this problem by using a new array to memorize the new replaced num and check if it has appeared before,if it has appeared before and isn't 1 then return false.
A:So what's the size of the array you are going to create to memorize.
B:The constraint of the of n is between 1 and 2 to the power of 31
,so we can estimate the max digit is 10 so the max ditgit squared sum would be 810.
A:Great! But the time complexity is according to your method ,
is the a way to lower it?
B:Maybe we can try to check the duplication by using hash map,creat a length of 810 integer array ,and also a digit squared sum function.
A:interviewee
B:interviewer
A:這邊我希望你去做出個power的function,也就是x的n次方,他的條件限制會如檔案所示。
B:好那我們要來寫一個x的n次方的函式,最直觀的解法就是用一個迴圈去將答案相乘幾次。
A:你這樣做的時間複雜度是O(n),那有沒有降低他時間複雜度的方式?
B:先來看看條件有什麼限制,x有正有負的而且是個double,n的話可以分正負基偶去討論,
所以我們這邊呼叫自己,所以可以考慮用遞迴的方式去做,所以我們要找到終止條件,那我們可以去設定n等於0時回傳,而接下來根據四種n的值狀況分別去做各自的遞迴呼叫。