Leetcode日記(1)

        有段時間沒有寫代碼了,就上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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章