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

首頁 > 學院 > 開發(fā)設(shè)計 > 正文

Leetcode日記(1)

2019-11-10 18:40:19
字體:
供稿:網(wǎng)友

        有段時間沒有寫代碼了,就上Leetcode練練手,先做幾個簡單的題目開個頭,從其中也發(fā)現(xiàn)了自己的一些不足,感覺自己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類型的數(shù)據(jù),有幾種求解方法,筆者選擇的是暴力求解,或者可以通過哈希表的方法求解,但是筆者對于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.

分析

       需要考慮負數(shù)和翻轉(zhuǎn)溢出的情況,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.

分析

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

解答

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; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 大理市| 弋阳县| 崇仁县| 获嘉县| 阿拉善右旗| 栖霞市| 荥经县| 克东县| 高邑县| 南澳县| 新密市| 夏津县| 红安县| 桑植县| 无锡市| 景宁| 邻水| 巧家县| 张北县| 九台市| 板桥市| 政和县| 惠东县| 靖边县| 克山县| 长海县| 长汀县| 确山县| 辽宁省| 沙湾县| 满城县| 海宁市| 舞钢市| 芦溪县| 霍林郭勒市| 靖州| 隆化县| 丰城市| 嘉善县| 开封市| 江阴市|