国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode日記(1)

2019-11-10 18:18:20
字體:
來源:轉載
供稿:網友

        有段時間沒有寫代碼了,就上Leetcode練練手,先做幾個簡單的題目開個頭,從其中也發現了自己的一些不足,感覺自己STL也該開始慢看了。

Two Sum

問題描述

       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的一些東西還不是很了解,只能暫時望而卻步。寫代碼的時候要考慮問題無解的情況。

解答

class Solution {public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; for (int i = 0; i < nums.size(); i++) { const int gap = target - nums[i]; for (int j = i + 1; j < nums.size(); j++) { if (gap == nums[j]) { result.push_back(i); result.push_back(j); return result; } } } throw "No two sum solution"; }};

Reverse Integer

問題描述

       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類型,比較時借用常量后綴。

解答

class Solution {public: int reverse(int x) { long long result = 0; while (x) { result = result * 10 + x % 10; x /= 10; } if (result > 2147483647LL || result < -2147483648LL) return 0; return result; }};

Palindrome Number

問題描述

       Determine whether an integer is a palindrome. Do this without extra space.

分析

       可以使用翻轉再比較的方法,或者依次取第一位和最后一位來比較。負數不屬于回文數。

解答

class Solution {public: bool isPalindrome(int x) { if (x < 0) return false; int reverse = 0; int origin = x; while (x) { reverse *= 10; reverse += x % 10; x /= 10; } return reverse == origin; }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 凌海市| 邯郸市| 徐水县| 汽车| 襄汾县| 府谷县| 盐源县| 任丘市| 白朗县| 甘南县| 佳木斯市| 孝昌县| 屏边| 黄陵县| 遵化市| 九江市| 阳朔县| 河池市| 公主岭市| 凤山市| 云梦县| 清涧县| 城市| 昌江| 洞头县| 调兵山市| 巩义市| 收藏| 珠海市| 江永县| 泗水县| 仁怀市| 中牟县| 广饶县| 贵州省| 沁阳市| 思茅市| 平安县| 顺义区| 清镇市| 会昌县|