leetcode 刷題(java版本)
阿新 • • 發佈:2018-11-07
1、leetcode 1
給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。
你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution { public int[] twoSum(int[] nums, int target) { int[] res = { 0, 0 }; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { res[0] = i; res[1] = j; } } } return res; } }
2、leetcode 7 反轉整數
給定一個 32 位有符號整數,將整數中的數字進行反轉。
示例 1:
輸入: 123 輸出: 321
示例 2:
輸入: -123 輸出: -321
示例 3:
輸入: 120 輸出: 21
注意:
假設我們的環境只能儲存 32 位有符號整數,其數值範圍是 [−231, 231 − 1]。根據這個假設,如果反轉後的整數溢位,則返回 0。
class Solution { public int reverse(int x) { long result = 0; while (x != 0){ result = result * 10 + x % 10; x = x / 10; } if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){ return 0; } return (int)result; } }
注意:這裡的result用來存放反轉後的結果,使用long型別。(如果使用int,當x過大時,反轉後result會出現溢位,例如x=1534236469,
反轉後result應為9646324351,但Integer.MAX_VALUE=2147483647,導致溢位,最終result=1056389759,這不是我們想要的結果,
所以這裡使用long,判斷溢位時,返回result=0)