LeedCode-Easy 1,7,9,13,14,20


因本人才疏学浅,如有错误之处,还请见谅

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].

翻译:

给你一组整数,返回一个指数,两个数字加起来是一个目标数

已经确保,每一个输入都有一个确定的一个解.不可能有两个一样的解

我的一开始的代码如下:

自己写的代码

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    vector<int> a;
    int flag = 0;
    //用两个for循环来判断是不是成立的
    for (int i = 0; i < nums.size(); i++) {
        int w = target - nums[i];
        for (int j = i + 1; j < nums.size(); j++) {
            if (nums[j] == w) {
                flag = 1;
                a.push_back(i);
                a.push_back(j);
                break;
            }
        }
        if (flag)
            break;
        
    }
    return a;
    }
};

他人的优秀代码—地址如下

优秀的代码

https://leetcode.com/problems/two-sum/discuss/674/C%2B%2B-one-pass

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> indices;
        //这里用unordered是因为这个查找起来快
        for (int i = 0; i < nums.size(); i++) {
        //如果这里没有这个值
            if (indices.find(target - nums[i]) != indices.end()) {
                //就把这个值,保存到indices里面
                return {indices[target - nums[i]], i};
            }
            indices[nums[i]] = i;
        }
        return {};
    }
};

Reverse Integer1

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1](显示错误,懂的都懂). For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

翻译

给你一个32位的数,要你把这个数字颠覆一下

需要注意的是:

我们输入的只能是一个32位的有符号的数,在INT的范围之内:

下面是我从Microsoft上查阅到的文档

https://docs.microsoft.com/zh-cn/cpp/c-language/cpp-integer-limits?view=vs-2019

INT_MINint 类型的变量的最小值。-2147483647 - 1
INT_MAXint 类型的变量的最大值。2147483647

官方的解释代码如下

代码

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            //这种情况是指,最后的一位余数大于7了
            if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            //这种情况是指,最后的一位数字小于了-8
            if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            //其他的就是一个标准的逆置函数s
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

Palindrome Number

题目原文

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true

Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Follow up:

Coud you solve it without converting the integer to a string?

翻译:

代码

①字符串的解法-自己写的

//字符串的解法
class Solution {
public:
    bool isPalindrome(int x) {
        string a = to_string(x);
        for (int i = 0; i < a.size() / 2; i++) {
            int j = a.size() - i-1;
            if (a[i] != a[j])
                return false;
        }
        return true;
    }
};

②不用字符串的写法

我自己的写出来想法不好,但是有一个大佬写的很不错

地址贴下:

https://leetcode.com/problems/palindrome-number/discuss/5165/An-easy-c%2B%2B-8-lines-code-(only-reversing-till-half-and-then-compare)

他的思路我讲一下,就是把这个数倒过来算,看看和原来的数,相等不相等,把一个数倒过来比较容易

代码如下:

//非字符串的解法
class Solution {
public:
    bool isPalindrome(int x) {
        //如果x<0或者x是一个单位数
        if (x < 0 || (x != 0 && x % 10 == 0)) return false;
        int sum = 0;
        //如果x>sum
        //而且这个算法只要算一半就OK了
        while (x > sum)
        {   
            //这是一个非常经典的小技巧了,算  "回文"
            sum = sum * 10 + x % 10;
            x = x / 10;
        }
        //x==sum就是表示x是偶数位,x=sum/10就是表明x是奇数位
        return (x == sum) || (x == sum / 10);
    }
};

Roman to Integer

题目原文

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

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

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

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

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

简单分析:

就是根据罗马的写字规则,要你把罗马数字,翻译为,阿拉伯数字

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

规则如下:

① 上图是字符喝和他代表的值,我们规定值越大的,等级越高

② 两个相同等级的字符在一起,就视为相加,等价高的在等级低的前面的时候也视为相加

例如: II 代表 2 VI 代表 6

③ 等级低的字符在等级高的字符前面的时候视为相减.

例如 :IV 代表 4

代码

下面是我用map写的代码:

class Solution {
public:
    int romanToInt(string s) {
        map<char, int> m;
        //添加对应的值
        m['I'] = 1;
        m['V'] = 5;
        m['X'] = 10;
        m['L'] = 50;
        m['C'] = 100;
        m['D'] = 500;
        m['M'] = 1000;
        //index就是我们上一个表示的等级
        int sum = 0,index=1;
        //从结尾到开头遍历一遍
        for (int i = s.length()-1; i >= 0; i--) {
            //大于就加
            if (m[s[i]] >= index) {
                sum += m[s[i]];
                index = m[s[i]];
            }
            //小于就减
            else {
                sum -= m[s[i]];
            }
        }
        return sum;
    }
};

下面是大佬的代码

地址如下:

https://leetcode.com/problems/roman-to-integer/discuss/6851/Simple-56ms-C%2B%2B-solution

class Solution {
public:
    int romanToInt(string s) {
        if (s.empty()) { return 0; }
        //用unordered_map就是因为他快
        unordered_map<char, int> mp{ {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} };
        int sum = mp[s.back()]; //用s的最后一个字符的键值,用来当sum,然后用sum来比较
        for (int i = s.size() - 2; i >= 0; --i) {
            //就是一个前一个的键值,是否大于后一个,大于就加,小于就减
            sum += mp[s[i]] >= mp[s[i + 1]] ? mp[s[i]] : -mp[s[i]];
        }
        return sum;
    }
};

Longest Common Prefix

题目原文

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Note:

All given inputs are in lowercase letters a-z.

题目大意

写一个函数,用来找到最长的相同前缀,在一组字符串中 如果没有相同的前缀,就返回""

我的代码如下:

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string a="";
        bool flag = true;
        int i;
        int index = 0;
        int Min = 999999;
        if (strs.empty())    return "";
        //找出最小的那个函数的长度
        for (int i = 0; i < strs.size(); i++) {
            if (strs[0].length() < index) {
                Min = strs[0].length();
                index = i;
            }
        }
        //两个for循环来判断
        for (i = 0; i < strs[index].length(); i++) {
            for (int j = 1; j < strs.size(); j++) {
                if (strs[0][i] != strs[j][i]) {
                    flag = false;
                    break;
                }
            }
            if (flag == true) {
                a += strs[0][i];
            }
            else
            {
                return a;
            }
        }
        return a;
    }
};

大佬的代码如下:

先贴地址

https://leetcode.com/problems/longest-common-prefix/discuss/6950/Clean-7-lines-C%2B%2B

思路解析

它利用了是前缀,sort函数 还有一个我感觉差不多,不过它把寻找的封装成了一个方法

class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        if(strs.empty()) return "";
        sort(strs.begin(), strs.end());
        string a = strs[0], b = strs.back();
        int i = 0;
        for(; i < min(a.size(), b.size()); i++) if(a[i] != b[i]) break;
        return a.substr(0, i);
    }
};

Valid Parentheses

题目原文:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

题目大意:

题目的意思是 有效的括号

给一段字符串,只要 '(', ')', '{', '}', '[' 几个字符,决定如果这个输入的字符是有效的

一个输入的字符串是有效的:

① 打开一个括号,就必须关闭一个括号

② 打开括号一定要按照争取的顺序

我的代码如下:

思路如下

看到这题,就想到了stack(栈)

注意点:

① 如果输入的是单个字符 ‘]’ ,要加栈是否为空的判断

这次我的代码喝大佬的代码都差不多,我就不贴了

class Solution {
public:
    bool Judge(char a, char b) {
        if (a == '(' && b == ')')
            return true;
        if (a == '{' && b == '}')
            return true;
        if (a == '[' && b == ']')
            return true;
        return false;
    }
    bool isValid(string s) {
        string leftBrackets, rightBrackets;
        leftBrackets = "({[";
        rightBrackets = ")}]";
        stack <char> Data;
        if (s.empty())   return true;

        for (int i = 0; i < s.size(); i++) {
            if (leftBrackets.find(s[i]) != string::npos)
                Data.push(s[i]);
            else {
                if (Data.empty())       //这个就如果 只要一个 ]  字符
                    return false;
                char a = Data.top();
                if (!Judge(a, s[i])) {
                    return false;
                }
                Data.pop();
            }
        }
        if (Data.empty())
            return true;
        else
            return false;
    }
};

如果这篇文章对你有张帮助的话,请给我点个免费的赞吧.

如果你有任何建议,或者是发现了我的错误,欢迎评论留言指出.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值