不得不开始刷LeetCode了,为了使小白的自尊心不受到毁灭性的打击,所以打算从最简单的题开始刷。现把所有题目的Python和Java代码都放在这儿,以便随时回忆。分两种语言的原因在于,Python是我最熟悉也是私心里最喜欢的语言,Java是受众面最广也是我希望学习的语言。以下完全按照LeetCode简单题的顺序出现。预计分5篇博文整理完毕。
题目目录
1. 两数之和
给定一个整数数组
nums
和一个目标值target
,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。示例:给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict = {}
for i, v in enumerate(nums):
if v in dict:
return [dict[v], i]
else:
dict[target - v] = i
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++){
int comp = target - nums[i];
if(map.containsKey(comp)){
return new int[] {map.get(comp), i};
}
map.put(nums[i], i);
}
return new int[] {0,0};
}
}
7. 整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1: 输入: 123 输出: 321
示例 2: 输入: -123 输出: -321
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if -10 < x < 10:
return x
str_x = str(x)
if str_x[0] == "-":
result = -((int)(str_x[1:][::-1]))
else:
result = (int)(str_x[::-1])
if((pow(-2,31) < x < pow(2,31)-1) & (pow(-2,31) < result < pow(2,31)-1)):
return result
else:
return 0
class Solution {
public int reverse(int x) {
int reverse = 0;
while(x != 0){
int ge = x % 10;
x /= 10;
if((reverse > Integer.MAX_VALUE/10) || (reverse == Integer.MAX_VALUE / 10 && ge > 7))
return 0;
if((reverse < Integer.MIN_VALUE/10) || (reverse == Integer.MIN_VALUE / 10 && ge < -8))
return 0;
reverse = reverse * 10 + ge;
}
return reverse;
}
}
9. 回文数
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1: 输入: 121 输出: true
示例 2: 输入: -121 输出: false 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
class Solution:
def isPalindrome(self, n):
"""
:type x: int
:rtype: bool
"""
p=n
k=0
if n < 0:
return False
while p!=0:
k=k*10+p%10
p=p//10
if k==n:
return True
else:
return False
class Solution {
public boolean isPalindrome(int x) {
if(x < 0){
return false;
}
String s = String.valueOf(x);
String ss = new StringBuilder(s).reverse().toString();
if(ss.equals(s)){
return true;
}else{
return false;
}
}
}
13. 罗马数字转整数
罗马数字包含以下七种字符:
I
,V
,X
,L
,C
,D
和M
。字符 数值 I 1 V 5 X 10 L 50 C 100 D 500 M 1000
例如, 罗马数字 2 写做
II
,即为两个并列的 1。12 写做XII
,即为X
+II
。 27 写做XXVII
, 即为XX
+V
+II
。通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做
IIII
,而是IV
。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为IX
。这个特殊的规则只适用于以下六种情况:
I
可以放在V
(5) 和X
(10) 的左边,来表示 4 和 9。X
可以放在L
(50) 和C
(100) 的左边,来表示 40 和 90。C
可以放在D
(500) 和M
(1000) 的左边,来表示 400 和 900。给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
输入: "LVIII" 输出: 58 解释: L = 50, V= 5, III = 3.
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
sum=0
convert={'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
for i in range(len(s)-1):
if convert[s[i]]<convert[s[i+1]]:
sum=sum-convert[s[i]]
else:
sum=sum+convert[s[i]]
return sum+convert[s[-1]]
class Solution {
public int romanToInt(String s) {
int sum=0, i;
char ch[] = s.toCharArray();
for(i=0;i<ch.length;i++)
{
switch(ch[i])
{
case 'I':
sum += 1;
break;
case 'V':
if(i!=0 && ch[i-1] == 'I')
sum += 4-1;
else
sum += 5;
break;
case 'X':
if(i!=0 && ch[i-1] == 'I')
sum += 9-1;
else
sum += 10;
break;
case 'L':
if(i!=0 && ch[i-1] == 'X')
sum += 40 -10;
else
sum += 50;
break;
case 'C':
if(i!=0 && ch[i-1] == 'X')
sum += 90-10;
else
sum += 100;
break;
case 'D':
if(i!=0 && ch[i-1] == 'C')
sum += 400-100;
else
sum += 500;
break;
case 'M':
if(i!=0 && ch[i-1] == 'C')
sum += 900-100;
else
sum += 1000;
break;
}
}
return sum;
}
}
14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串
""
。示例 1: 输入: ["flower","flow","flight"] 输出: "fl"
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
if len(strs) == 1:
return strs[0]
minl = min([len(x) for x in strs])
end = 0
while end < minl:
for i in range(1,len(strs)):
if strs[i][end]!= strs[i-1][end]:
return strs[0][:end]
end += 1
return strs[0][:end]
class Solution {
public String longestCommonPrefix3(String[] strs) {
if (strs == null || strs.length == 0)
return "";
if (strs.length == 1)
return strs[0];
int length = strs[0].length();
for (String str : strs) {
length = Math.min(length, str.length());
}
if (length == 0)
return "";
StringBuilder result = new StringBuilder(length);
for (int j = 0; j < length; j++) {
for (int i = 1; i < strs.length; i++) {
if (strs[i].charAt(j) != strs[0].charAt(j))
return result.toString();
}
result.append(strs[0].charAt(j));
}
return result.toString();
}
}
20. 有效的括号
给定一个只包括
'('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
mapping = {")":"(", "}":"{", "]":"["}
for char in s:
if char in mapping:
top = stack.pop() if stack else '#'
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack
class Solution {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
char[] chs=s.toCharArray();
int len=chs.length;
if((len&1)==1)return false;
for(int i=0;i<len;i++){
if(stack.isEmpty()||!isMatch(stack.peek(),chs[i]))
stack.push(chs[i]);
else
stack.pop();
}
return stack.isEmpty();
}
public boolean isMatch(char a,char b){
switch(a){
case '(': if(b == ')') return true; else return false;
case '{': if(b == '}') return true; else return false;
case '[': if(b == ']') return true; else return false;
default : return false;
}
}
}
21. 合并两个有序链表
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
ret = l1
ret.next = self.mergeTwoLists(l1.next, l2)
else:
ret = l2
ret.next = self.mergeTwoLists(l1, l2.next)
return ret
class Solution {
class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode head = null;
if (l1.val <= l2.val){
head = l1;
head.next = mergeTwoLists(l1.next, l2);
} else {
head = l2;
head.next = mergeTwoLists(l1, l2.next);
}
return head;
}
}
26. 删除排序数组中的重复项
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
示例 1:给定数组 nums = [1,1,2], 函数应该返回新的长度 2, 并且原数组 nums 的前两个元素被修改为
1
,2
。 你不需要考虑数组中超出新长度后面的元素。
class Solution:
def removeDuplicates(self, nums):
if len(nums) <= 1:
return len(nums)
s = 0
for f in range(1, len(nums)):
if nums[s] != nums[f]:
s += 1
nums[s] = nums[f]
return s + 1
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0)
return 0;
int i = 0;
for(int j = 1; j < nums.length; j++){
if(nums[j] != nums[i]){
i++;
nums[i] = nums[j];
}
}
return i+1;
}
}
27. 移除元素
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
示例 1: 给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 你不需要考虑数组中超出新长度后面的元素。
class Solution:
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
l = len(nums)
if l == 0:
return 0
i = 0
while i < l:
if nums[i] == val:
nums.pop(i)
l-=1
else:
i+=1
return len(nums)
class Solution {
public int removeElement(int[] nums, int val) {
int i = 0;
for(int j = 0; j < nums.length; j++) {
if(nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
}
28. 实现strStr()
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1: 输入: haystack = "hello", needle = "ll" 输出: 2
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
l = len(needle)
for i in range(len(haystack)-l+1):
if haystack[i:i+l] == needle:
return i
return -1
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")){
return 0;
}
int len = needle.length();
for(int i = 0; i < haystack.length()-len+1; i++){
if(haystack.substring(i, i+len).equals(needle)){
return i;
}
}
return -1;
}
}
35. 搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1: 输入: [1,3,5,6], 5 输出: 2
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target in nums:
return nums.index(target)
else:
if target < nums[0]:
return 0
elif target > nums[-1]:
return len(nums)
else:
for i in range(len(nums)-1):
if nums[i] < target < nums[i+1]:
return i+1
class Solution {
public int searchInsert(int[] nums, int target) {
int i;
if( nums.length==0){
return 0;
}
for(i=0;i<nums.length;i++){
if(target<=nums[i]){
break;
}
}
return i;
}
}
38. 报数(最无聊的题目,没有之一,不接受反驳)
报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1
被读作"one 1"
("一个一"
) , 即11
。11
被读作"two 1s"
("两个一"
), 即21
。21
被读作"one 2"
, "one 1"
("一个二"
,"一个一"
) , 即1211
。
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
res = ["1"]
for i in range(n):
num = res[i]
temp = num[0]#当前的值
count = 0#计数
ans = ""#第n+1个数字的结果
for j in range(0,len(num)):
if num[j] == temp:
count += 1
else:
ans += str(count)
ans += str(temp)
temp = num[j]
count = 1
ans += str(count)
ans += str(temp)
res.append(ans)
return res[n-1]
class Solution {
public String next(String num) {
String ans = "";
int i = 0;
while (i < num.length()) {
char ch = num.charAt(i);
int cnt = 0;
while (i < num.length() && ch == num.charAt(i)) {
i++;
cnt++;
}
ans += cnt;
ans += ch;
}
return ans;
}
public String countAndSay(int n) {
String num = "1";
while (--n > 0) {
num = next(num);
}
return num;
}
}
53. 最大子序和
给定一个整数数组
nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum = 0
MaxSum = nums[0]
for i in range(len(nums)):
sum += nums[i]
if sum > MaxSum:
MaxSum = sum
if sum < 0:
sum = 0
return MaxSum
class Solution {
public static int maxSubSum5(int[] a) {
int maxSum = 0;
int tempSum = 0;
int begin = 0;
for (int i = 0; i < a.length; i++) {
if (tempSum > 0)
tempSum += a[i];
else {
tempSum = a[i];
begin = i; //标记
}
if (tempSum > maxSum) {
maxSum = tempSum;
//可以在这里获取最佳连续子序列和的起点位置begin和重点位置i
}
}
return maxSum;
}
}
58. 最后一个单词的长度
给定一个仅包含大小写字母和空格
' '
的字符串,返回其最后一个单词的长度。如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例: 输入: "Hello World" 输出: 5
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
temp_list = s.split(" ")
for i in temp_list[::-1]:
if i != "":
return len(i)
return 0
class Solution {
public int lengthOfLastWord(String s) {
String [] str = s.split(" ");
int length = str.length;
if (length == 0){
return 0;
}
return str[length-1].length();
}
}
66. 加一
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123。
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits_str = ''.join(str(s) for s in digits)
digits_int = int(digits_str)
result_int = digits_int + 1
x = []
for i in str(result_int):
x.append(int(i))
return x
class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
for(int i=len-1;i>=0;i--){
if(digits[i]<9){
digits[i]+=1;
return digits;
}
digits[i] = 0;
}
int [] res = new int[len+1];
res[0]=1;
return res;
}
}
67. 二进制求和
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字
1
和0
。示例 1: 输入: a = "11", b = "1" 输出: "100"
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return str(bin(int(a,2)+int(b,2)))[2:]
class Solution {
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int al = a.length()-1;
int bl = b.length()-1;
int carry = 0;
while( al >=0 || bl >=0 )
{
int sum = carry;
if(al >= 0)
{
sum += (a.charAt(al) - '0');
al--;
}
if(bl >= 0)
{
sum += (b.charAt(bl) - '0');
bl--;
}
result.append(sum%2); //相加结果
carry = sum /2; //进位,如果是1那么carry=0,如果是2则要进位给下面一位+1
}
if(carry !=0 ) //都相加完了,还要进位的情况
result.append(1);
return result.reverse().toString(); //先反转,再输出
}
}
69. x 的平方根
实现
int sqrt(int x)
函数。计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1: 输入: 4 输出: 2
示例 2: 输入: 8 输出: 2 说明: 8 的平方根是 2.82842..., 由于返回类型是整数,小数部分将被舍去。
class Solution:
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
left=0
right=x
while left<right:
mid=int((left+right)/2)
if x<mid**2:
right=mid
else:
left=mid+1
if left>1:
return left-1
else:
return left
class Solution {
public int mySqrt(int x) {
long low = 0;
long high = x/2+1;//平方根的值按规律发现不会大于它的中值+1。这样每个查找就少了一次
long tmp;
long mid = 1;
while (low <= high)
{
mid = (low + high) / 2;
tmp = mid * mid;
if (tmp == x)
return (int)mid;
else if (tmp > x)
high = mid - 1;
else if (tmp < x)
low = mid + 1;
}
return (int)high;
}
}
70. 爬楼梯(斐波那契数列)
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
注意:给定 n 是一个正整数。
示例 1: 输入: 2 输出: 2 解释: 有两种方法可以爬到楼顶。 1. 1 阶 + 1 阶 2. 2 阶
class Solution:
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
condition = [0] * (n + 1)
condition[0] = 1
condition[1] = 1
for i in range(2, n+1):
condition[i] = condition[i-1] + condition[i-2]
return condition[n]
class Solution {
public int climbStairs(int n) {
if (n == 1)
return 1;
else if (n == 2)
return 2;
else {
int[] ans = new int[n];
ans[0] = 1;
ans[1] = 2;
for(int i=2;i<n;i++) {
ans[i]=ans[i-1]+ans[i-2];
}
return ans[n-1];
}
}
}
83. 删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1: 输入: 1->1->2 输出: 1->2
示例 2: 输入: 1->1->2->3->3 输出: 1->2->3
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:#链表为空
return head
cur=head
while cur.next:#下一节点不为空
if cur.val==cur.next.val:#第一次判断,头元素与头元素下一节点的值是否相等。。。
cur.next=cur.next.next
else:
cur=cur.next
return head
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null)
return head;
ListNode node = head;
while (node.next != null) {
if (node.val == node.next.val)
node.next = node.next.next;
else
node = node.next;
}
return head;
}
}
88. 合并两个有序数组
给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。
说明:
- 初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
- 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
示例: 输入: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 输出: [1,2,2,3,5,6]
class Solution:
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
end = m + n -1
m-=1
n-=1
while end >= 0 and m >= 0 and n >= 0:
if nums1[m] >= nums2[n]:
nums1[end] = nums1[m]
m-=1
else:
nums1[end] = nums2[n]
n-=1
end-=1
while n >= 0:
nums1[end] = nums2[n]
n-=1
end-=1
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int end = m + n -1;
m-=1;
n-=1;
while (end >= 0 && m >= 0 && n >= 0){
if (nums1[m] >= nums2[n]){
nums1[end] = nums1[m];
m-=1;
}
else{
nums1[end] = nums2[n];
n-=1;
}
end-=1;
}
while (n >= 0){
nums1[end] = nums2[n];
n-=1;
end-=1;
}
}
}
100. 相同的树
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] 输出: true
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p == None and q == None:
return True
if p == None or q == None:
return False
if p.val == q.val:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
else:
return False
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> queue=new LinkedList<>();
queue.add(p);
queue.add(q);//两个树的节点进队列
while(!queue.isEmpty()){
TreeNode f=queue.poll();//出队列,如果队列头为空,返回null
TreeNode s=queue.poll();
if(f==null&&s==null) continue;
else if(f == null || s == null || f.val != s.val) return false;
queue.add(f.left);
queue.add(s.left);
queue.add(f.right);
queue.add(s.right);
}
return true;
}
}
101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树
[1,2,2,3,4,4,3]
是对称的。1 / \ 2 2 / \ / \ 3 4 4 3
但是下面这个
[1,2,2,null,3,null,3]
则不是镜像对称的:1 / \ 2 2 \ \ 3 3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.ismirror(root,root)
def ismirror(self,l_root,r_root):
if l_root==None and r_root==None:
return True
if l_root==None or r_root==None:
return False
if l_root.val==r_root.val:
return self.ismirror(l_root.left,r_root.right) and self.ismirror(l_root.right,r_root.left)
return False
def ismirror2(self,l_root,r_root):
qlist=[]
qlist.append(l_root)
qlist.append(r_root)
while len(qlist)!=0:
t1=qlist.pop()
t2=qlist.pop()
if(t1==None and t2==None):
continue
if(t1==None or t2==None):
return False
if(t1.val!=t2.val):
return False
qlist.append(t1.left)
qlist.append(t2.right)
qlist.append(t1.right)
qlist.append(t2.left)
return True
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while(!q.isEmpty()){
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if(t1 == null && t2 == null) continue;
if(t1 == null || t2 == null) return false;
if(t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}
}
104. 二叉树的最大深度
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import javafx.util.Pair;
import java.lang.Math;
class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
107. 二叉树的层次遍历 II
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:给定二叉树
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
返回其自底向上的层次遍历为:[ [15,7], [9,20], [3] ]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return [] #为空则返回空列表
queue=[root] #使用列表实现队列的功能,首先存储root
res=[]
while queue: #当queue不为空时
nodes=[] #存节点,每次循环前置空,每次只装一部分
node_values=[] #存节点的值
for node in queue:
if node.left:
nodes.append(node.left)
if node.right:
nodes.append(node.right)
node_values+=[node.val]
res=[node_values]+res
queue=nodes
return res
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> result=new ArrayList();
List<TreeNode> list=new ArrayList();
if(root==null) return result;
list.add(root);
while(!list.isEmpty()){
List<Integer> curList=new ArrayList();//每次当前层节点都要重新初始化
List<TreeNode> nextList=new ArrayList();//初始化下一层所有节点的list
for(TreeNode cur:list){//cur是当前节点,list是当前层的所有节点
curList.add(cur.val);
if(cur.left!=null) nextList.add(cur.left);//下一层节点
if(cur.right!=null) nextList.add(cur.right);//下一层节点
}
list=nextList;
result.add(0,curList);//当前层所有节点的list倒插进返回结果中
}
return result;
}
}
108. 将有序数组转换为二叉搜索树
将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
示例:
给定有序数组: [-10,-3,0,5,9], 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树: 0 / \ -3 9 / / -10 5
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None;
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = self.sortedArrayToBST(nums[:mid])
root.right = self.sortedArrayToBST(nums[mid+1:])
return root
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null) {
return null;
}
return convertTree(nums, 0, nums.length - 1);
}
private TreeNode convertTree(int[] nums, int l, int r) {
if (l <= r) {
int mid = (l + r) / 2;
TreeNode newNode = new TreeNode(nums[mid]);
newNode.left = convertTree(nums, l, mid - 1);
newNode.right = convertTree(nums, mid + 1, r);
return newNode;
}
else {
return null;
}
}
}
110. 平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。
示例 1:
给定二叉树
[3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
返回
true
。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
elif abs(self.height(root.left)-self.height(root.right))>1:
return False
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)
def height(self,root):
if root == None:
return 0
else:
return max(self.height(root.left),self.height(root.right))+1
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.math.*;
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null)
return true;
int leftH = getHeight(root.left);
int rightH = getHeight(root.right);
int diff = leftH - rightH;
if(diff>1 || diff<-1){
return false;
}else{
return isBalanced(root.left) && isBalanced(root.right);
}
}
int getHeight(TreeNode root){
if(root == null){
return 0;
}
return 1+Math.max(getHeight(root.left),getHeight(root.right));
}
}
111. 二叉树的最小深度
给定一个二叉树,找出其最小深度。最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树
[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7
返回它的最小深度 2.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is None and root.right is None:
return 1
elif root.left is None:
return 1 + self.minDepth(root.right)
elif root.right is None:
return 1 + self.minDepth(root.left)
else:
return 1 + min([self.minDepth(root.left), self.minDepth(root.right)])
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
if (root.left == null && root.right == null) return 1;
int left, right;
if (root.left != null) left = minDepth(root.left);
else left = Integer.MAX_VALUE;
if (root.right != null) right = minDepth(root.right);
else right = Integer.MAX_VALUE;
return Math.min(left, right) + 1;
}
}
112. 路径总和
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
返回
true
, 因为存在目标和为 22 的根节点到叶子节点的路径5->4->11->2
。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root == None:
return False
if root.left == None and root.right == None:
return sum == root.val
elif root.right == None and root.left != None:
return self.hasPathSum(root.left, sum-root.val)
elif root.left == None and root.right != None:
return self.hasPathSum(root.right, sum-root.val)
else:
return self.hasPathSum(root.left, sum-root.val) or \
self.hasPathSum(root.right, sum-root.val)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
// 根节点为空 直接返回false
if (root == null) {
return false;
}
// 终止条件: 找到叶子节点 并且叶子节点路径长度等于sum(叶子节点值=sum - 之间的路径长)
if (root.left == null && root.right == null) {
if (sum == root.val) {
return true;
}
return false;
}
// 没有达到条件,判断左右子树是否符合
boolean result = true;
if (hasPathSum(root.left, sum - root.val)) {
return true;
}
if (hasPathSum(root.right, sum - root.val)) {
return true;
}
//不符合则返回false
return false;
}
}
118. 杨辉三角
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
res = []
for i in range(numRows):
temp = [1] *(i + 1)
res.append(temp)
for j in range(1, i):
res[i][j] = res[i-1][j-1] + res[i-1][j]
return res
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list_All = new ArrayList<List<Integer>>();
if(numRows < 1) return list_All;
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list_All.add(list1);
for(int i=2; i <= numRows; i++){
List<Integer> list = new ArrayList<Integer>();
list.add(1);
List<Integer> list_pre = list_All.get(i-2);
for(int j=1;j<i-1;j++) {
list.add(list_pre.get(j-1)+list_pre.get(j));
}
list.add(1);
list_All.add(list);
}
return list_All;
}
}
119. 杨辉三角 II
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
class Solution:
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
p = [1]
if not rowIndex:
return p
for j in range(rowIndex):
p = [1] + [p[i]+p[i+1] for i in range(len(p)-1)] +[1]
return p
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> list=new ArrayList<Integer>();
for(int i=0;i<=rowIndex;i++){
list.add(1);
for(int j=i-1;j>=1;j--){
list.set(j, list.get(j)+list.get(j-1) );
}
}
return list;
}
}
121. 买卖股票的最佳时机
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。注意你不能在买入股票前卖出股票。
示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
profit = 0
minimum = prices[0]
for i in prices:
minimum = min(i, minimum)
profit = max(i - minimum, profit)
return profit
class Solution {
public int maxProfit(int[] prices) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for(int i = 0; i < prices.length; i++){
if (prices[i] < minprice)
minprice = prices[i];
else if(prices[i] - minprice > maxprofit)
maxprofit = prices[i] - minprice;
}
return maxprofit;
}
}
122. 买卖股票的最佳时机 II
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1: 输入: [7,1,5,3,6,4] 输出: 7 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxprofit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i-1]:
maxprofit += prices[i] - prices[i-1]
return maxprofit
class Solution {
public int maxProfit(int[] prices) {
int maxprofit = 0;
for(int i = 1; i < prices.length; i++){
if(prices[i] > prices[i-1])
maxprofit += prices[i] - prices[i-1];
}
return maxprofit;
}
}
125. 验证回文串
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
说明:本题中,我们将空字符串定义为有效的回文串。
示例 1: 输入: "A man, a plan, a canal: Panama" 输出: true
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = list(filter(str.isalnum, s.lower()))
return True if s == s[::-1] else False
class Solution {
public boolean isPalindrome(String s) {
char[] cha = s.toCharArray();
int i = 0, j = cha.length - 1;
while(i < j){
if(!Character.isLetterOrDigit(cha[i]))
i++;
else if(!Character.isLetterOrDigit(cha[j]))
j--;
else
if(Character.toLowerCase(cha[i]) == Character.toLowerCase(cha[j])){
i++;
j--;
}else{
return false;
}
}
return true;
}
}
136. 只出现一次的数字
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1: 输入: [2,2,1] 输出: 1
class Solution:
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 0
for num in nums:
result = result ^ num
return result
class Solution {
public int singleNumber(int[] nums) {
int ret = nums[0];
for (int i = 1; i < nums.length; ++i) {
ret ^= nums[i];
}
return ret;
}
}
141. 环形链表
给定一个链表,判断链表中是否有环。为了表示给定链表中的环,我们使用整数
pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果pos
是-1
,则在该链表中没有环。示例 1:输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if slow == fast:
return True
return False
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
判断是否为环形链表:用追赶的方法,设定两个指针slow、fast,从头指针开始,每次分别前进1步、2步。如存在环,则两者相遇;如不存在环,fast遇到NULL退出。
155. 最小栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
- push(x) -- 将元素 x 推入栈中。
- pop() -- 删除栈顶的元素。
- top() -- 获取栈顶元素。
- getMin() -- 检索栈中的最小元素。
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = None
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if self.min == None or self.min > x:
self.min = x
def pop(self):
"""
:rtype: void
"""
popItem = self.stack.pop()
if len(self.stack) == 0:
self.min = None
return popItem
if popItem == self.min:
self.min = self.stack[0]
for i in self.stack:
if i < self.min:
self.min = i
return popItem
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min
class MinStack {
private int min_val = Integer.MAX_VALUE;
private Stack<Integer> s = new Stack<>();
/** initialize your data structure here. */
public MinStack() {}
public void push(int x) {
if (x <= min_val) {
s.push(min_val);
min_val = x;
}
s.push(x);
}
public void pop() {
if (s.pop() == min_val) min_val = s.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
return min_val;
}
}
160. 相交链表
编写一个程序,找到两个单链表相交的起始节点。
例如,下面的两个链表:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3 在节点 c1 开始相交。
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
lenA, lenB = 0, 0
pA = headA
pB = headB
while pA:
pA = pA.next
lenA += 1
while pB:
pB = pB.next
lenB += 1
pA = headA
pB = headB
if lenA > lenB:
for i in range(lenA-lenB):
pA = pA.next
else:
for i in range(lenB-lenA):
pB = pB.next
while pA!=pB:
pA = pA.next
pB = pB.next
return pA
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode p1 = headA;
ListNode p2 = headB;
while (p1!=null&&p2!=null){
p1=p1.next;
p2=p2.next;
}
while (p1!=null){
headA=headA.next;
p1=p1.next;
}
while (p2!=null){
headB=headB.next;
p2=p2.next;
}
while (headA!=null&&headB!=null){
if(headA==headB){
return headA;
}
headA=headA.next;
headB=headB.next;
}
return null;
}
}
167. 两数之和 II - 输入有序数组
给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。
说明:
- 返回的下标值(index1 和 index2)不是从零开始的。
- 你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
示例: 输入: numbers = [2, 7, 11, 15], target = 9 输出: [1,2] 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
s = {}
r = []
for i in range(len(numbers)):
if numbers[i] in s.keys():
r.append(s[numbers[i]]+1)
r.append(i+1)
return r
s[target-numbers[i]] = i
return None
class Solution {
public int[] twoSum(int[] numbers, int target) {
int left=0,right=numbers.length-1;
while(left<right){
if(numbers[left]+numbers[right]>target)
right--;
else if(numbers[left]+numbers[right]<target)
left++;
else
return new int[]{left+1,right+1};
}
return null;
}
}
168. Excel表列名称
给定一个正整数,返回它在 Excel 表中相对应的列名称。例如,
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ...
示例 1: 输入: 1 输出: "A"
class Solution:
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = ""
while n != 0:
result = chr((n-1)%26+65) + result
n = (n-1)/26
return result
class Solution {
public String convertToTitle(int n) {
String s = "";
while (n != 0) {
int temp = (n-1) % 26;
s = (char) ('A' + temp) + s;
n = (n-1) / 26;
}
return s;
}
}
169. 求众数
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于
⌊ n/2 ⌋
的元素。你可以假设数组是非空的,并且给定的数组总是存在众数。示例 1: 输入: [3,2,3] 输出: 3
class Solution(object):
def majorityElement(self, nums):
res=set(nums)
n=len(nums)/2
for item in res:
if(nums.count(item)>n):
return item
class Solution {
public int majorityElement(int[] nums) {
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
int n = nums.length;
for(int num : nums) //统计每个元素出现的次数
{
Integer count = map.get(num);
if(count == null)
count =1;
else
count++;
map.put(num,count);
if(map.get(num) > n/2)
return num;
}
return 0;
}
}
// 看到一个神答案
// class Solution {
// public int majorityElement(int[] nums) {
// Arrays.sort(nums);
// return nums[nums.length / 2];
// }
// }
171. Excel表列序号
给定一个Excel表格中的列名称,返回其相应的列序号。例如,
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
示例 1: 输入: "A" 输出: 1
class Solution:
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for letter in s:
result = result * 26 + ord(letter) - ord('A') + 1
return result
class Solution {
public int titleToNumber(String s) {
int sum = 0;
if(s == null) return -1;
for(char c : s.toUpperCase().toCharArray()) {
sum *= 26;
sum += c - 'A' + 1;
}
return sum;
}
}
172. 阶乘后的零
给定一个整数 n,返回 n! 结果尾数中零的数量。
示例 1: 输入: 3 输出: 0 解释: 3! = 6, 尾数中没有零。
class Solution:
def trailingZeroes(self, n):
"""
:type n: int
:rtype: int
"""
r = 0
while n >= 5:
n = n // 5
r+=n
return r
class Solution {
public int trailingZeroes(int n) {
if (n <= 1) {
return 0;
}
int result = 0;
while (n != 0) {
result += n / 5;
// 注意:需要得到每个数分解质因子后5的个数
n = n / 5;
}
return result;
}
}
175. 组合两个表
表1:
Person
+-------------+---------+ | 列名 | 类型 | +-------------+---------+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +-------------+---------+ PersonId 是上表主键
表2:
Address
+-------------+---------+ | 列名 | 类型 | +-------------+---------+ | AddressId | int | | PersonId | int | | City | varchar | | State | varchar | +-------------+---------+ AddressId 是上表主键 编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:FirstName, LastName, City, State
select FirstName, LastName, City, State from Person left join Address on Person.PersonId=Address.PersonId;
176. 第二高的薪水
编写一个 SQL 查询,获取
Employee
表中第二高的薪水(Salary) 。+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述
Employee
表,SQL查询应该返回200
作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回null
。+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
SELECT
(SELECT DISTINCT
Salary
FROM
Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1) AS SecondHighestSalary
;
181. 超过经理收入的员工
Employee
表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。+----+-------+--------+-----------+ | Id | Name | Salary | ManagerId | +----+-------+--------+-----------+ | 1 | Joe | 70000 | 3 | | 2 | Henry | 80000 | 4 | | 3 | Sam | 60000 | NULL | | 4 | Max | 90000 | NULL | +----+-------+--------+-----------+
给定
Employee
表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。+----------+ | Employee | +----------+ | Joe | +----------+
# Write your MySQL query statement below
SELECT Worker.Name AS Employee
FROM Employee AS Worker, Employee AS Manager
WHERE Worker.ManagerId = Manager.Id AND Worker.Salary > Manager.Salary
182. 查找重复的电子邮箱
编写一个 SQL 查询,查找
Person
表中所有重复的电子邮箱。示例:
+----+---------+ | Id | Email | +----+---------+ | 1 | a@b.com | | 2 | c@d.com | | 3 | a@b.com | +----+---------+
根据以上输入,你的查询应返回以下结果:
+---------+ | Email | +---------+ | a@b.com | +---------+
说明:所有电子邮箱都是小写字母。
Select Email From Person Group By Email Having Count(*) > 1
183. 从不订购的客户
某网站包含两个表,
Customers
表和Orders
表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
Customers
表:+----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+
Orders
表:+----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+
例如给定上述表格,你的查询应返回:
+-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
select C.name Customers
from Customers C
where C.id not in (Select CustomerId from Orders)
189. 旋转数组
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
示例 1: 输入:
[1,2,3,4,5,6,7]
和 k = 3 输出:[5,6,7,1,2,3,4]
解释: 向右旋转 1 步:[7,1,2,3,4,5,6]
向右旋转 2 步:[6,7,1,2,3,4,5]
向右旋转 3 步:[5,6,7,1,2,3,4]
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
k=k%len(nums)
nums[:]=nums[len(nums)-k:]+nums[:len(nums)-k]
class Solution {
public void rotate(int[] nums, int k) {
int len = nums.length;
k = k % len;
reverse(nums, 0, len - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, len - 1);
}
public static void reverse(int[] nums, int l, int r) {
while (l < r) {
int t = nums[l];
nums[l] = nums[r];
nums[r] = t;
l++;
r--;
}
}
}
190. 颠倒二进制位(移位)
颠倒给定的 32 位无符号整数的二进制位。
示例:
输入: 43261596 输出: 964176192 解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 , 返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
x = bin(n)[2:].zfill(32) # zfill返回指定长度的字符串,原字符串右对齐,前面填充0
z = x[-1::-1]
y = int(z, 2)
return y
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int result = n;
for(int i = 0;i<32;i++){
result <<= 1;
result = result | n&1;
n >>= 1;
}
return result;
}
}
191. 位1的个数
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
示例 :
输入: 11 输出: 3 解释: 整数 11 的二进制表示为00000000000000000000000000001011
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count('1') #转换后二进制是字符串
public int hammingWeight(int n) {
int result=0;
while(n!=0){
if((n&1)==1){
result++;
n=n>>>1;
}
else{
n=n>>>1;
}
System.out.println(n);
}
return result;
}