辣雞劉的LeetCode之旅-1 [two Sum算法,反轉整數算法,迴文數,羅馬數轉整數]

從今天開始,辣雞劉學習一下搞搞算法,確定了leetcode網站,從最簡單的開始學習和思考。
入門算法,

1. 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.
舉例:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

簡單翻譯:
給定一個整數數組和一個目標值,找出數組中和爲目標值的兩個數。你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。

雖然很簡單,但是已經好久沒寫過Java的辣雞劉也寫了十幾分鍾,而且複雜度相當高,不推薦大家用,別問我爲啥沒用Python,因爲昨晚沒寫出來(逃

class Solution {
public int[] twoSum(int[] nums, int target) {
首先獲取數組長度
int len=nums.length;
兩個循環進行遍歷
for (int i=0;i < len;i++)
{
    for (int j=i+1;j < len;j++)
    因爲同樣的元素不能重複使用,所以j從1開始
    {
        if (target == nums[i]+nums[j])
        {
            return new int[] {i, j};
        }
        }
    }
    我試過了,這句話得加着
    throw new IllegalArgumentException("No such nunbers");
}
}

複雜度分析:

時間複雜度:O(n^2), 對於每個元素,我們試圖通過遍歷數組的其餘部分來尋找它所對應的目標元素,這將耗費 O(n) 的時間。因此時間複雜度爲 O(n^2)。
空間複雜度:O(1)。
另外這是我的Python版本,不知道爲啥一直報錯,有算法好的兄弟可以指導一二,謝謝了

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        l=len(nums);
        for i,j in l:
            if (target=nums[i]+nums[j]) and (i!=j) :
                return [i,j]

2. 整數反轉

題目描述:
Given a 32-bit signed integer, reverse digits of an integer.
給定一個 32 位有符號整數,將整數中的數字進行反轉。
實例:

輸入: 123
輸出: 321

輸入: -123
輸出: -321

輸入: 120
輸出: 21

冗長而又原始的代碼來了,這次我用Python做的,起初想用一些函數,但是爲了更原始一些,所以儘量避免函數的選用:
思路很簡單:將輸入的整數轉爲字符串,反向遍歷,再組合成整數;其中按照正負數分了兩個判斷:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        res_list = [];
        list2=[];
        str1=str(x);
        str_list=list(str1);
        l=len(str_list);
        if str_list[0] is '-':
            print('負數');
            for i in str_list[::-1]:
                res_list.append(i);
                res = "".join(res_list);
            res_list.remove('-')
            res_list.insert(0, '-');
            res = "".join(res_list);
            print(res);
        else:
            print('正常情況');
            for i in str_list[::-1]:
                res_list.append(i);
            print("".join(res_list));
            res = "".join(res_list);
        if abs(int(res))>2147483647:
            print('越界')
            return 0
        else:
            print('最終返回:',res)
            return int(res);

當然如果用函數的話,簡單:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        s = int(str(abs(x))[::-1])
        if s > 2147483647 or s < -2147483648 :
            return 0
        return s if x > 0 else -s

3. 迴文數

描述:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。

示例 1:

輸入: 121
輸出: true
示例 2:

輸入: -121
輸出: false
解釋: 從左向右讀, 爲 -121 。 從右向左讀, 爲 121- 。因此它不是一個迴文數。
示例 3:

輸入: 10
輸出: false
解釋: 從右向左讀, 爲 01 。因此它不是一個迴文數。

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x<0:
            print('no')
            return False;
        else:
            x = abs(x);
            str_x = str(x);
            str_list = list(str_x);
            bool_list = [];
            str_len = 0;
            if (str_list[-1] is '0') & (len(str_list)>1):
                str_list.remove('0');
                str_len = len(str_list);
                return False;
            else:
                str_len = len(str_list);
                for i in range(str_len):
                    print(str_list[i], str_list[str_len - i - 1]);
                    if str_list[i] is str_list[str_len - i - 1]:
                        bool_list.append('True');
                    else:
                        bool_list.append('False');
                if 'False' in bool_list:
                    return False;
                else:
                    return True;

4. 羅馬數字的轉換

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

思路:將羅馬數字轉換成對應的整數。首先將羅馬數字翻轉,從小的開始累加,如果遇到CM(M-C=1000-100=900)這種該怎麼辦呢?因爲翻轉過來是MC,M=1000先被累加,所以使用一個last變量,把M記錄下來,如果下一個數小於M,那麼減兩次C,然後將C累加上,這個實現比較巧妙簡潔。

class Solution:
    def romartoInt(self,s):
        values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000};
        sum = 0;
        last = None;
        for i in s[::-1]:
            print(i)
            if last and values[i] < last:
                sum = sum - 2 * values[i];
            sum = sum + values[i]
            last = values[i]
        print(sum)
        return sum
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章