461. Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
1 | Input: x = 1, y = 4 |
问题
求两个数的二进制表示中,不同位数的个数。
思路
1 | class Solution { |
476. Number Complement
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
The above arrows point to positions where the corresponding bits are different.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
Example 1:
1 | Input: 5 |
Example 2:
1 | Input: 1 |
问题
取一个正整数的二进制表达的反
思路
- 制作一个mask 将正整数的二进制位数对应的位数 置为0;
- 将正整数取反 与 ~mask(00000000111)作与运算
C++
1 | class Solution { |
190. Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
For example
given1
input 43261596 (represented in binary as 00000010100101000001111010011100)
1 | , return 964176192 (represented in binary as 00111001011110000010100101000000). |
Follow up:
If this function is called many times, how would you optimize it?
问题
反转比特
思路
- 每次取最后一位加入result
- 再将imput右移抛出已加入的数字
C++
1 | uint32_t reverseBits(uint32_t input) |
500. Keyboard Row
Given a List of words, return the words that can be typed using letters of alphabet on only one row’s of American keyboard like the image below.
Example 1:
1 | Input: ["Hello", "Alaska", "Dad", "Peace"] |
Note:
You may use one character in the keyboard more than once.
You may assume the input string will only contain letters of alphabet.
问题
给你一列表的单词,返回那些只包含美式键盘一行的单词
思路
查每个单词的第一个字母,将其设为某行,随后遍历每个字母,看是否都在那一行
C++
1 | std::vector<std::string> findWords(std::vector<std::string> &words) |
收获
==using namespace std; or using std::xxxxx;==
412. Fizz Buzz
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
1 | n = 15, |
问题
给一个N 从1到n中的数 放入数组,如果是三的倍数输出Fizz,五的倍数输出Buzz,三五的倍数输出FizzBuzz
思路
分支判断
C++
1 | using namespace std; |
收获
==to_string()== int=>string
别人写法
1 | vector<string> fizzBuzz(int n) { |
344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
1 | Given s = "hello", return "olleh". |
C++
1 | string reverseString(string s) { |
别人写法
1 | string reverseString(string s) { |
收获
1 | swap函数 |
496. Next Greater Element I
You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.
The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.
Example 1:
1 | Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. |
Example 2:
1 | Input: nums1 = [2,4], nums2 = [1,2,3,4]. |
Note:
All elements in nums1 and nums2 are unique.
The length of both nums1 and nums2 would not exceed 1000.
C++
1 | vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { |
别人写法
通过建立一个键值对,预先保存nums中每个数的nextGreaterElement,随后对其进行查找。
1 | class Solution { |
463. Island Perimeter
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.
Example:
1 | [[0,1,0,0], |
问题
0是海1是岛,求岛的边界
思路
从非边缘行,列开始遍历,遍历到1,count++,检查其左上两个是否也为一,若为1记录为一个repeat,
C++
1 | int islandPerimeter(vector<vector<int>>& grid) { |
收获
遍历二维vector的方法
1 | for (int i=0; i<grid.size(); i++) |
292. Nim Game
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
Hint:
If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?
问题
取石头 一个人能取1,2,3块石头,如果你是先手,判断是否能赢
思路
是4的倍数必输
C++
1 | bool canWinNim(int n) { |
收获
1 | (n % 4) != 0 |
485. Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
1 | Input: [1,1,0,1,1,1] |
Note:
The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000
问题
求最长的连续1的数量
思路
做一个mark数组标记0的位置,再进行处理
C++
1 | int findMaxConsecutiveOnes(vector<int>& nums) { |
别人写法
1 | int findMaxConsecutiveOnes(vector<int>& nums) { |
收获
别想太复杂
136. Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
问题
求一个数组中的单个数字,要求线性时间复杂度,无额外空间
思路
异或为0
C++
1 | int singleNumber(vector<int>& nums) { |
收获
多关注位运算,异或,与,非,反
448. Find All Numbers Disappeared in an Array
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.
Example:
1 | Input: |
问题
寻找数组中消失的数字
思路
把数字放到该放的地方,然后找出消失的数字
C++
1 | vector<int> findDisappearedNumbers(vector<int>& nums) { |
520. Detect Capital
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like “USA”.
All letters in this word are not capitals, like “leetcode”.
Only the first letter in this word is capital if it has more than one letter, like “Google”.
Otherwise, we define that this word doesn’t use capitals in a right way.
Example 1:
1 | Input: "USA" |
Example 2:
1 | Input: "FlaG" |
Note:
The input will be a non-empty word consisting of uppercase and lowercase latin letters.
问题
看string是否符合标准大写规则
思路
分支判断
C++
1 | bool detectCapitalUse(string word) { |
别人写法
1 | public boolean detectCapitalUse(String word) { |
收获
通过ASC码判断,大写字母的ASC码比小写字母小。
104. Maximum Depth of Binary Tree
问题
求树的最大深度
思路
深度优先||广度优先
C++
1 | 深度优先 |
389. Find the Difference
问题
寻找两个字符串不同的字符
思路
位运算 异或能找出单个不同的字符
C++
1 | char findTheDifference(string s, string t) { |
收获
异或找不同
371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.
Example:
Given a = 1 and b = 2, return 3.
问题
在不使用+ -的情况下 实现加法
思路
通过异或来实现0+1或1+0,通过与并左移实现进位
C++
1 | int getSum(int a, int b) { |
收获
可以通过异或来实现0+1或1+0,通过与+左移实现进位
226. Invert Binary Tree
1 | Invert a binary tree. |
问题
翻转二叉树
思路
递归,非递归(广度优先)
C++
1 | 递归 |
收获
swap函数
258. Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
问题
38-》3+8=11》1+1》2 一个数,各位数相加,直至只剩一位数
思路
C++
1 | int addDigits(int num) { |
收获
12345 % 9 = (1 + 2 + 3 + 4 +5 ) % 9
492. Construct the Rectangle
For a web developer, it is very important to know how to design a web page’s size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
1 | 1. The area of the rectangular web page you designed must equal to the given target area. |
Example:
1 | Input: 4 |
Note:
The given area won’t exceed 10,000,000 and is a positive integer
The web page’s width and length you designed must be positive integers
问题
给定一个正方形面积,求出符合要求的一组长款
收获
时间复杂度,的优化
C++
1 | 写法1:99ms |
收获
不用系统函数,想办法替代
283. Move Zeroes
Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
问题
将数组中的0移动到数组末尾
思路
遇到非0就覆盖原数组,最后再将0添上
C++
1 | void moveZeroes(vector<int>& nums) { |
506. Relative Ranks
Given scores of N athletes, find their relative ranks and the people with the top three highest scores, who will be awarded medals: “Gold Medal”, “Silver Medal” and “Bronze Medal”.
Example 1:
1 | Input: [5, 4, 3, 2, 1] |
Note:
N is a positive integer and won’t exceed 10,000.
All the scores of athletes are guaranteed to be unique.
问题
根据数组中的得,输出其对应的排名
思路
利用C++ map的递增特性,进行输出
C++
1 | vector<string> findRelativeRanks(vector<int>& nums) { |
收获
C++ map是递增的,it—>first是key it->second是value,倒序遍历迭代器的方法
1 | for(map<int,int>::reverse_iterator it=mp.rbegin();it!+mp.rend();it++) |
530. Minimum Absolute Difference in BST
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
1 | Input: |
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
问题
求二叉搜索树中,求两个结点绝对值相差最小的值
思路
中序遍历出的二叉搜索树是有序递增的,在这个有序的队列中求最小值
C++
1 | public:void inorderTraverse(TreeNode* root, int& val, int& min_dif) { |
收获
中序遍历二叉搜索树是有序的
167. Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Input:
numbers={2, 7, 11, 15}, target=9
Output:
index1=1, index2=2
问题
给一个数组,给一个目标,找出相加为目标数的两个数在数组中的位置
描述
一左一右两个指针, while
C++
1 | vector<int> twoSum(vector<int>& numbers, int target) { |
521. Longest Uncommon Subsequence I
Given a group of two strings, you need to find the longest uncommon subsequence of this group of two strings. The longest uncommon subsequence is defined as the longest subsequence of one of these strings and this subsequence should not be any subsequence of the other strings.
A subsequence is a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Trivially, any string is a subsequence of itself and an empty string is a subsequence of any string.
The input will be two strings, and the output needs to be the length of the longest uncommon subsequence. If the longest uncommon subsequence doesn’t exist, return -1.
Example 1:
1 | Input: "aba", "cdc" |
Note:
Both strings’ lengths will not exceed 100.
Only letters from a ~ z will appear in input strings.
问题
两个字符串中最长的字符串是否是第二个字符串的子串,如果是则返回-1,否做返回其长度
C++
1 | int findLUSlength(string a, string b) { |
455. Assign Cookies
Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.
Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.
Example 1:
1 | Input: [1,2,3], [1,1] |
Example 2:
1 | Input: [1,2], [1,2,3] |
问题
给小孩分曲奇,两个数组
第一个是小孩的需求数组【1,2,3】,代表有3个小孩,分别要1,2,3大小的曲奇
第二个是自己拥有的曲奇数组【1,2】代表有2个曲奇,大小分别为1,2
思路
贪心算法,先对两个数组进行递增排序,随后开始比较,作一个关于饼干数组的循环,如果遇到合适的小孩,则分配给他,然后对下一个下小孩进行分析
C++
1 | int findContentChildren(vector<int>& g, vector<int>& s) { |
收获
贪心算法,sort函数
453. Minimum Moves to Equal Array Elements
Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
Example:
1 | Input: |
Explanation:
Only three moves are needed (remember each move increments two elements):
1 | [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4] |
问题
给一组n个数,每次只能进行n-1个数的+1操作,问将他们都变为相同的数字最少需要几步。
思路
(min+k)n = sum+k(n-1)
k = sum - min*n
C++
1 | int minMoves(vector<int>& nums) { |
别人写法
1 | int minMoves(vector<int>& nums) { |
收获
列出等式,找规律
1 | #include <numeric> |
383. Ransom Note
Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
Each letter in the magazine string can only be used once in your ransom note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct(“a”, “b”) -> false
canConstruct(“aa”, “ab”) -> false
canConstruct(“aa”, “aab”) -> true
问题
给两个数组,如果能用第二个数组中的元素构成第一个数组,则返回true
思路
对数组2的每一个字母进行计数+1,计数完后再对数组1对应进行计数-1,如果有数计数<0,则返回false,否则则返回true
C++
1 | bool canConstruct(string ransomNote, string magazine) { |
收获
一种比较的思路
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
Subscribe to see which companies asked this question.
问题
给2个数组,找出共同的元素
思路
比较,去除重复元素 使用unique
C++
1 | vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { |
收获
1 | 去除重复元素 |
404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
1 | 3 |
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
问题
统计一棵树的左叶子和
思路
递归
C++
1 | int sumOfLeftLeaves(TreeNode* root) { |
收获
从最小的一部分观察,制定递归策略
122. Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
问题
给一个数组,数组i代表天数,a[i-1]代表当天股票价值,问怎么样才能获取最大值?
思路
累加差值,如果遇到下跌的天数就跳过
C++
1 | int maxProfit(vector<int> &prices) |
别人的写法
1 | int maxProfit(vector<int> &prices) { |
收获
1 | if (prices[i] < prices[i+1]) |
387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
1 | s = "leetcode" |
问题
求string中第一个不重复的字符的下标
思路
使用map将string按字符一个个存入map,并count
C++
1 | int firstUniqChar(string s) { |
收获
多用键值对,通过
1 | for (int i = 0; i< s.size(); i++) { |
能实现按顺序查找第一个不重复的字符。
122. Best Time to Buy and Sell Stock II
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
问题
给定一个数组 下标为天数,各个元素为当天股票价格,球可获利的最大值
思路
累加
C++
1 | int maxProfit(vector<int> &prices) { |
171. Excel Sheet Column Number
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
1 | A -> 1 |
问题
类似于Excel的列标题,求其代表的数字
思路
按位数分析累加
C++
1 | int titleToNumber(string s) { |
237. Delete Node in a Linked Lis
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
问题
删除节点
思路
用被删除结点之后的结点替换被删除结点
C++
1 | void deleteNode(ListNode* node) { |
100. Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
问题
判断两棵树是否相等
思路
递归判断
C++
1 | bool isSameTree(TreeNode* p, TreeNode* q) { |
169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array
问题
求一个数组中,出现次数超过一半的字符
思路
排序后,出现次数超过一半的字符肯定在中间
C++
1 | public: |
别人的写法
1 | int majorityElement(vector<int>& nums) { |
242. Valid Anagram
Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
问题
两个数组,问他们是否重新组合后是否为同一个单词
思路
对第二个数组中的字母一一计数,随后再对第一个数组中的字母一一扣除,如果为负,则false
C++
1 | bool isAnagram(string s, string t) { |
504. Base 7
Given an integer, return its base 7 string representation.
1 | Example 1: |
问题
给一个数,转化为7进制数
思路
递除取余
C++
1 | string convertToBase7(int num) { |
409. Longest Palindrome
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example “Aa” is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
1 | Input: |
问题
求能组成的最长回文子串的长度
思路
统计所有偶数长度的字符并相加,统计所有奇数长度的字符并减一相加,只保留一个奇数不减一
C++
1 | int longestPalindrome(string s) { |
217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
问题
给一个数字数组,如果有重复的则返回true
思路
统计,遇到超过1的返回
C++
1 | bool containsDuplicate(vector<int>& nums) { |
13. Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
问题
转化罗马数字
思路
做一个字典,分小紧随大,大紧随小 两种罗马字符减加情况
C++
1 | public: |
401. Binary Watch
A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59).
Each LED represents a zero or one, with the least significant bit on the right.
For example, the above binary watch reads “3:25”.
Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
Example:
1 | Input: n = 1 |
问题
二进制手表,当亮点个数为n时,给出所有时间组合
思路
二进制表示各时间,符合count则添加进返回vector
C++
1 | vector<string> readBinaryWatch(int num) { |
收获
bitset<10>10>
emplace_back 比 push_back 更高效
206. Reverse Linked List
问题
翻转链表
思路
设立一个pre指针,一个next指针,进行翻转
C++
1 | ListNode* reverseList(ListNode* head) { |
###