有段時間沒有寫代碼了,就上Leetcode練練手,先做幾個簡單的題目開個頭,從其中也發現了自己的一些不足,感覺自己STL也該開始慢看了。
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
測試樣例是vector類型的數據,有幾種求解方法,筆者選擇的是暴力求解,或者可以通過哈希表的方法求解,但是筆者對于STL的一些東西還不是很了解,只能暫時望而卻步。寫代碼的時候要考慮問題無解的情況。
Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
需要考慮負數和翻轉溢出的情況,long的類型也是32bit的,所以選擇long long類型,比較時借用常量后綴。
Determine whether an integer is a palindrome. Do this without extra space.
可以使用翻轉再比較的方法,或者依次取第一位和最后一位來比較。負數不屬于回文數。
新聞熱點
疑難解答