leetcode 1-20 easy
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路:
关键词:一遍迭代map
建立map,迭代一遍数组,第一个迭代开始检查numToFind是否存在于map中。存在就返回两者的index;
不存在就把当前的数组nums[i]插入到map。重复迭代下去。 C++:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
unordered_map<int,int> hash_map;
for(int i=;i<nums.size();i++)
{
int numToFind=target-nums[i];
if(hash_map.find(numToFind)!=hash_map.end())
{
res.push_back(i);
res.push_back(hash_map[numToFind]);
return res;
}
else
hash_map[nums[i]]=i;
}
return res;
}
};
python:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
maps={}
for i in range(len(nums)):
if target-nums[i] in maps:
return i,maps[target-nums[i]]
else:
maps[nums[i]]=i
return -1,-1
7、Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321Example 2:
Input: -123
Output: -321Example 3:
Input: 120
Output: 21Note:
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.
C++:
class Solution {
public:
int reverse(int x) {
long long res = ;
while(x) {
res = res* + x%;
x /= ;
}
return (res<INT_MIN || res>INT_MAX) ? : res;
}
};
python:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
""" if x < 0:
result = (0 - int(str(0-x)[::-1]))
if result <= 2147483647 and result >= -2147483648:
return result
else:
return 0
else:
result = int(str(x)[::-1])
if result <= 2147483647 and result >= -2147483648:
return result
else:
return 0
9、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: trueExample 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?
C++
//思路:反转后一样
class Solution {
public:
bool isPalindrome(int x) {
if(x<0|| (x!=0 &&x%10==0)) return false;
int sum=0;
int x1=x;
while(x)
{
sum = sum*10+x%10;
x = x/10;
}
return (x1==sum);
}
};
python
def isPalindrome(self, x):
if x < 0:
return False
p, res = x, 0
while p:
res = res * 10 + p % 10
p /= 10
return res == x
14、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
.
C++
First one: check from strs[][] to strs[i][]. If matches, check strs[][] to strs[i][].
思路:ans由0开始添加前缀
Code: class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==)
return "";
string ans="";
int max=INT_MAX;
for(auto& s:strs)
{
max=(max>s.length())?s.length():max;
}
for(int i=;i<max;i++)
{
bool flag=true;
char x=strs[][i];
for(auto& s:strs)
{
if(s[i]!=x)
{
flag=false;
break;
}
}
if(flag==false)
return ans;
ans+=x;
}
return ans;
}
}; ////////////////////////////////////////////////// Second one: assume the prefix is strs[]. Compair with strs[i], and cut the letters which don’t match.
ans由最小的串开始不断减少前缀
Code: class Solution {
public:
string longestCommonPrefix(vector<string>& strs) {
if(strs.size()==)
return "";
string ans=strs[];
int max=INT_MAX;
for(auto& s:strs)
{
if(s.length()==)
return "";
int i=;
for(i=;i<ans.length()&&i<s.length();i++)
{
if(s[i]!=ans[i])
break; //跳出整个循环
}
ans=ans.substr(,i);
} return ans;
}
}; //////////////////////////////////// Third one: use a Trie data structure to save the strs. Search the trie, and stops when a TrieNode has more than one son.
数据结构trie
Code: class TrieNode{
public:
bool val;
TrieNode* next[];
int sons;
TrieNode() :val(false), sons()
{
for (int i = ; i < ; i++)
next[i] = nullptr;
}
}; class Trie{
private:
TrieNode* putst(string& s, TrieNode * node, int loc, TrieNode *father)
{
if (s.length() == )
{
node->val = true;
node->sons++;
return node;
}
if (node == nullptr)
{
node = new TrieNode();
if (father != nullptr)
father->sons++;
}
if (loc == s.length())
{
node->val = true;
return node;
}
if (s[loc] >= 'a')
node->next[s[loc] - 'a'] = putst(s, node->next[s[loc] - 'a'], loc + , node);
else
node->next[s[loc] - 'A' + ] = putst(s, node->next[s[loc] - 'A' + ], loc + , node);
return node;
} public:
TrieNode *root;
void insert(string & str){ putst(str, root, , nullptr); }
Trie(){ root = new TrieNode(); }
}; class Solution {
private:
string findPre(TrieNode * node)
{
if (node == nullptr || (node != nullptr&&node->sons > ))
return string("");
int i = ;
for (i = ; i < ; i++)
{
if (node->next[i] != nullptr)
break;
}
if (i == )
return string("");
char temp1 = ((i>) ? ('A' + i) : ('a' + i));
string temp;
temp.insert(temp.begin(), temp1);
if (node->val)
{
return string("");
}
else
{
return temp + findPre(node->next[i]);
}
} public:
string longestCommonPrefix(vector<string>& strs) {
Trie a;
for (auto& str : strs)
a.insert(str);
return findPre(a.root);
}
};
python:good trick
def longestCommonPrefix(strs):
if not strs:
return "" for i, letter_group in enumerate(zip(*strs)): #返回所有字符串各自第一个元素组成的第一组元祖,例如("a","a")
if len(set(letter_group)) > 1:
return strs[0][:i]
else: #如果长度不一样,for在最短的字符串结束并跳到else
return min(strs) strs=["abcd","adef"]
print(longestCommonPrefix(strs))
同c++的第二种方法
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
shortest = min(strs,key=len)
for i, ch in enumerate(shortest):
for other in strs:
if other[i] != ch:
return shortest[:i]
return shortest
20、Valid Parentheses
Given a string containing just the characters
'('
,')'
,'{'
,'}'
,'['
and']'
, determine if the input string is valid.An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: trueExample 2:
Input: "()[]{}"
Output: trueExample 3:
Input: "(]"
Output: falseExample 4:
Input: "([)]"
Output: falseExample 5:
Input: "{[]}"
Output: true
C++
class Solution {
public:
bool isValid(string s) {
stack<char> paren;
for (char& c : s) {
switch (c) {
case '(': paren.push(c); break;
case '{': paren.push(c); break;
case '[': paren.push(c); break;
case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;
case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
default: ; // pass
}
}
return paren.empty() ;
}
};
python
class Solution:
def isValid(self, s):
stack = []
dict = {"]":"[", "}":"{", ")":"("}
for char in s:
if char in dict.values():
stack.append(char)
elif char in dict.keys():
if stack == [] or dict[char] != stack.pop():
return False
else:
return False
return stack == []
leetcode 1-20 easy的更多相关文章
- 【LeetCode算法-20】Valid Parentheses
LeetCode第20题 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determin ...
- LeetCode:20. Valid Parentheses(Easy)
1. 原题链接 https://leetcode.com/problems/valid-parentheses/description/ 2. 题目要求 给定一个字符串s,s只包含'(', ')', ...
- [Leetcode][Python]20: Valid Parentheses
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 20: Valid Parentheseshttps://oj.leetcod ...
- leetcode contest 20
Q1: 520. Detect Capital Given a word, you need to judge whether the usage of capitals in it is right ...
- 【一天一道LeetCode】#20. Valid Parentheses
一天一道LeetCode系列 (一)题目 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ...
- LeetCode第[20]题(Java):Valid Parentheses
题目:有效的括号序列 难度:Easy 题目内容: Given a string containing just the characters '(', ')', '{', '}', '[' and ' ...
- LeetCode(20):有效的括号
Easy! 题目描述: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效. 有效字符串需满足: 左括号必须用相同类型的右括号闭合. 左括号必须以正确的顺序闭 ...
- 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题
我现在在做一个叫<leetbook>的免费开源书项目,力求提供最易懂的中文思路,目前把解题思路都同步更新到gitbook上了,需要的同学可以去看看 书的地址:https://hk029.g ...
- 【Leetcode】【Easy】String to Integer (atoi)
Implement atoi to convert a string to an integer. Hint: Carefully consider all possible input cases. ...
- 【Leetcode】【Easy】Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...
随机推荐
- express 4 使用session和cookies
https://my.oschina.net/u/1466553/blog/294336 http://blog.csdn.net/liyi109030/article/details/3527138 ...
- JeecgBoot 2.1.1 代码生成器AI版本发布,基于SpringBoot+AntDesign的JAVA快速开发平台
此版本重点升级了 Online 代码生成器,支持更多的控件生成,所见即所得,极大的提高开发效率:同时做了数据库兼容专项工作,让 Online 开发兼容更多数据库:Mysql.SqlServer.Ora ...
- PAT甲级——A1092 To Buy or Not to Buy【20】
Eva would like to make a string of beads with her favorite colors so she went to a small shop to buy ...
- 03_springmvc整合mybatis
一.整合思路 springmvc+mybaits的系统架构: 第一步整合dao层:mybatis和spring整合:通过spring管理mapper接口,使用mapper的扫描器自动扫描mapper接 ...
- java基础之final关键字
final: 意为终态.在java中得注意以下四点: 1.final是一个修饰符,可修饰变量,方法,类. 2.final修饰子类不可以被继承. 3.final修饰的方法不可以被重写(覆盖) 4.对于一 ...
- Python中的sort()
Python中的sort()方法用于数组排序,本文以实例形式对此加以详细说明: 一.基本形式列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可 ...
- 安卓手机--键盘谈起后 fixed背景图片被键盘顶起的问题
参考文章: vue写法: <div class="main" :style="{ height: bodyHeight + 'px' }"> < ...
- Apache Commons之commons-lang
org.apache.commons.lang3此包主要是高度可重用静态的工具方法,主要是对java.lang类的一些补充. package com.cxl.beanutil.test; import ...
- Elasticsearch快速开始
Elasticsearch是一个分布式RESTful风格的搜索和数据分析引擎 查询:Elasticsearch允许执行和合并多种类型的搜索——结构化.非结构化.地理位置.度量指标.搜索方式随心而变 分 ...
- css之页面三列布局之左右两边宽度固定,中间自适应
左右两边宽度固定,中间自适应 左右两边绝对定位 可以利用浮动,左边的左浮动,右边的右浮动 css3 flex布局(html http://www.cnblogs.com/myzy/p/5919814. ...