Hov's Blog

To code, To record, To recall.

【LeetCode】66. Plus One

题目描述: Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. You may assume the integer do not contain any leading zero, except the number 0 itself. The digits are stored such that the most significant digit is at the head of the list. 思路: 题目的意思是将数组当成一个整数,然后对这个整数加 1 ,返回结果。 比如,[9,9,9] 返回 [1,0,0,0] ; [9,9,8] 返回 [9,9,9] 。 从数组最右边开始遍历: 如果当前元素小于 8 ,则将当前元素加 1 后,直接返回数组 digits ; 如果当前元素等于 9 ,将当前元素置为 0 ,继续判断; 若遍历结束还没返回结果,说明数组 digits 内的元素全为 9 ,则创建一个新的数组,首位为 1 ,其余位为 0 ,返回新数组。

【LeetCode】58. Length of Last Word

题目描述: Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘, return the length of last word in the string. If the last word does not exist, return 0. Note: A word is defined as a character sequence consists of non-space characters only. Example: Input: “Hello World” Output: 5 思路: 从后往前遍历字符串。 注意字符串后面是否有空格,所以先判断字符串是否以空格结尾; 若当前字符不是空格,开始计数,直到遇到空格,返回计数的结果。 代码实现: class Solution { public int lengthOfLastWord(String s) { int count = 0; int i = s.

【LeetCode】35. Search Insert Position

题目描述: Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Here are few examples. [1,3,5,6], 5 → 2 [1,3,5,6], 2 → 1 [1,3,5,6], 7 → 4 [1,3,5,6], 0 → 0 思路: 大水题,通过二分查找实现。 注意:如果数组中找不到 target 。 要么 target 比当前元素小,返回当前元素的位置(mid)。因为数组后移,当前位置存放 target ; 要么 target 比当前元素大,返回当前元素的位置的后一个位置(mid+1)。

【LeetCode】682. Baseball Game

题目描述: You’re now a baseball game point recorder. Given a list of strings, each string can be one of the 4 following types: Integer (one round’s score): Directly represents the number of points you get in this round. ”+” (one round’s score): Represents that the points you get in this round are the sum of the last two valid round’s points. “D” (one round’s score): Represents that the points you get in this round are the doubled data of the last valid round’s points.

【LeetCode】532. K-diff Pairs in an Array

题目描述: Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: Input: [3, 1, 4, 1, 5], k = 2 Output: 2 Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).