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

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

Leetcode日記(1)

2019-11-10 18:31:32
字體:
供稿:網(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.

分析

       需要考慮負(fù)數(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)再比較的方法,或者依次取第一位和最后一位來比較。負(fù)數(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ā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 西贡区| 襄城县| 兴海县| 威远县| 长汀县| 通辽市| 长治市| 耒阳市| 西贡区| 清苑县| 清远市| 北流市| 西乡县| 视频| 涿州市| 石林| 改则县| 缙云县| 铜山县| 普兰店市| 大同县| 兴宁市| 定远县| 车致| 建宁县| 吐鲁番市| 双流县| 乐安县| 隆昌县| 万宁市| 江津市| 稻城县| 务川| 木里| 江永县| 乌兰浩特市| 黎城县| 东辽县| 柳州市| 鄱阳县| 江山市|