算法養成記:迴文數判斷

  • 2020 年 3 月 10 日
  • 筆記

LeetCode9

Palindrome Number

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

中文意思就是:判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。

Example 1:

Input: 121 Output: true

Example 2:

Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

進階:

你能不將整數轉為字符串來解決這個問題嗎?

在實際測試里,都加了特例的情況下

執行用時分別是:

7ms,7ms,9ms,6ms

內存消耗分別是:

40.6MB,40.9MB,40.4MB,40.8MB

不加特例的情況下,前面三種的效率都不太高,都是到了12-15ms左右,甚至更多。最後一種能降到10ms以下。

最讓我驚訝的是,6ms能擊敗100%Java版本代碼。和C,C++,Python相比,真是慘。

這一版文案您還覺得滿意嗎?

哪裡不太對,但又說不上來。

數據結構和算法一直都是程序員面試重點。寫好每一個方法,每一個接口,程序的效率也會越來越高。為了學習和鞏固數據結構和算法,我們特別創作了《呆萌程序員–明明凱凱算法養成記》,每天更新一篇數據結構知識點或者刷一道LeetCode題目。算法都會在LeetCode上測試。當然答案不唯一,由於能力有限,實現方法不一定是最好的,也希望各位小夥伴一起來學習分享~添加微信一起學習吧!