LeetCode题解(一)0001-0099

14. Longest Common Prefix


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

计算字符串数组的最长相同部分

###解法

注意考虑数组内只有一个元素、以及数组内有空字符的边界情况:

我先求出数组中最短字符串的长度,最长的相同字符串不多于这个长度。

如果不匹配则依次递减。

class Solution {

public String longestCommonPrefix(String[] strs) {

if (strs.length == 1)

return strs[0];

int minLength = 0;

for (int i = 0; i < strs.length; i++) {

if(strs[i].trim().length() == 0)

return “”;

if (minLength == 0) {

minLength = strs[i].length();

} else {

minLength = Math.min(minLength, strs[i].length());

}

}

String commonPrefix = “”;

for (int i = minLength; i >= 1; i–) {

for (int j = 0; j < strs.length; j++) {

if (commonPrefix.trim().length() == 0) {

commonPrefix = strs[j].substring(0, i);

} else if (!commonPrefix.equals(strs[j].substring(0, i))) {

commonPrefix = “”;

break;

}

}

if (commonPrefix.trim().length() != 0)

return commonPrefix;

}

return commonPrefix;

}

}

20. Valid Parentheses


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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

###解法

括号匹配,可以使用栈来解决。遍历到前括号,push对应的后括号到栈里面。

遇到后括号,与栈顶字符对比是否一致。如果栈空或者不匹配则返回false

遍历完毕,栈空则返回true.

class Solution {

public boolean isValid(String s) {

Stack stack = new Stack<>();

char[] ch = s.toCharArray();

for (char c : ch) {

if (c == ‘(’)

stack.push(‘)’);

else if (c == ‘[’)

stack.push(‘]’);

else if (c == ‘{’)

stack.push(‘}’);

else if (stack.isEmpty() || c != stack.pop())

return false;

}

return stack.isEmpty();

}

}

##21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

###Example

Input: 1->2->4, 1->3->4

Output: 1->1->2->3->4->4

###解法

使用递归求解。

/**

  • Definition for singly-linked list.

  • public class ListNode {

  • int val;
    
  • ListNode next;
    
  • ListNode(int x) { val = x; }
    
  • }

*/

class Solution {

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

if (l1 == null) return l2;

if (l2 == null) return l1;

if (l1.val < l2.val) {

l1.next = mergeTwoLists(l1.next, l2);

return l1;

} else {

l2.next = mergeTwoLists(l2.next, l1);

return l2;

}

}

}

##26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

###Example

Given nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.

It doesn’t matter what you leave beyond the new length.

###解法

删除重复的元素,返回新数组的长度。

不能使用新的数组,可以覆盖重复的元素。

nowNum 是当前正在比较的数值。

duplicateCount 是重复元素的个数。

realIndex 已整理到该下标的新数组。

class Solution {

public int removeDuplicates(int[] nums) {

if (nums.length <= 1)

return nums.length;

int nowNum = nums[0];

int duplicateCount = 0;

int realIndex = 0;

for (int i = 1; i < nums.length; i++) {

if (nums[i] == nowNum) {

duplicateCount += 1;

} else {

realIndex++;

nums[realIndex] = nums[i];

nowNum = nums[i];

}

}

return nums.length - duplicateCount;

}

}

##27. Remove Element

Given an array and a value, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

###Example

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

###解法

删除指定的元素,和26比较类似。

需要考虑边界情况。

class Solution {

public int removeElement(int[] nums, int val) {

if (nums.length == 0)

return 0;

if (nums.length == 1) {

if (nums[0] == val)

return 0;

else

return 1;

}

int nowIndex = 0;

for (int i = 0; i < nums.length; i++) {

if (nums[i] != val) {

nums[nowIndex] = nums[i];

nowIndex++;

}

}

return nowIndex;

}

}

##28. Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

###Example

Input: haystack = “hello”, needle = “ll”

Output: 2

Input: haystack = “aaaaa”, needle = “bba”

Output: -1

###TestCase

“”,“”

“h”,“”

“hello”,“ll”

“abcldll”,“ll”

“abcldllx”,“x”

“aaabb”,“baba”

“mississippi”,“issip”

###解法

首先判断边界情况。然后双重循环遍历匹配,注意下标越界情况。判断needle的第一位到最后一位与haystack相等则返回haystack的下标i

class Solution {

public int strStr(String haystack, String needle) {

int haystackLength = haystack.trim().length();

int needleLength = needle.trim().length();

if (needleLength == 0)

return 0;

if (haystackLength == 0 || haystackLength < needleLength)

return -1;

char[] ch1 = haystack.toCharArray();

char[] ch2 = needle.toCharArray();

for (int i = 0; i < ch1.length; i++) {

for (int j = 0; j < ch2.length; j++) {

if (i + j < ch1.length) {

if (ch1[i + j] != ch2[j]) {

break;

} else if (j == ch2.length - 1) {

return i;

}

} else {

return -1;

}

}

}

return -1;

}

}

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.

Example

Input: [1,3,5,6], 5

Output: 2

解法

这道题目比较简单,遍历数组,当target <=nums[i],返回此时的下标就可以了。

class Solution {

public int searchInsert(int[] nums, int target) {

if (nums.length == 0)

return 0;

for (int i = 0; i < nums.length; i++) {

if (target <= nums[i])

return i;

}

return nums.length;

}

}

38. Count and Say


The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
    
  2. 11
    
  3. 21
    
  4. 1211
    
  5. 111221
    

1 is read off as “one 1” or 11.

11 is read off as “two 1s” or 21.

21 is read off as “one 2, then one 1” or 1211.

Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

解法

题目看懂之后,就比较容易解决了。

第一个数字:1

第二个:上一个数字1:1个1,写成:11

第三个:上一个数字11:2个1,写成21

第四个:上一个数字21:1个2、1个1,写成1211

……

使用递归求解:

class Solution {

public String countAndSay(int n) {

if (n <= 1) {

return “1”;

} else {

String result = “”;

String str = countAndSay(n - 1);

char[] chars = str.toCharArray();

char nowChar = chars[0];

int nowCharCount = 0;

for (int i = 0; i < chars.length; i++) {

if (nowChar == chars[i]) {

nowCharCount++;

} else {

result = result + nowCharCount + nowChar;

nowChar = chars[i];

nowCharCount = 1;

}

if (chars.length - i == 1) {

result = result + nowCharCount + nowChar;

}

}

return result;

}

}

}

53. Maximum Subarray


Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],

the contiguous subarray [4,-1,2,1] has the largest sum = 6.

解法

这道题目不难想到解决方案,难的是时间复杂度。

我首先敲出来的代码是比较直接,比较费时的嵌套循环,直接超时了:

// Time Limit Exceeded

class Solution {

public int maxSubArray(int[] nums) {

if(nums.length == 1){

return nums[0];

}

int maxSum = nums[0];

for(int i = 0;i < nums.length;i++){

int nowSum = 0;

for(int j = i;j<nums.length;j++){

nowSum = nowSum + nums[j];

maxSum = Math.max(maxSum, nowSum);

}

}

return maxSum;

}

}

最终的解决方案,只用一次循环,Accepted:

// Accepted

class Solution {

public int maxSubArray(int[] nums) {

int maxSum = nums[0];

int nowSum = nums[0];

for (int i = 1;i < nums.length;++i){

nowSum = Math.max(nowSum + nums[i],nums[i]);

maxSum = Math.max(maxSum, nowSum);

}

return maxSum;

}

}

58. Length of Last Word


iven 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) {

if(s.trim().length() == 0)

return 0;

if(!s.contains(" ")){

return s.toCharArray().length;

} else {

String[] strs = s.split(" ");

String lastStr = strs[strs.length - 1];

return lastStr.toCharArray().length;

}

}

}

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.

Example

Input: [0] Output: [1]

Input: [0,9,1,6] Output: [0,9,1,7]

Input: [0,1,9] Output: [0,2,0]

Input: [9,9,9] Output: [1,0,0,0]

Input: [] Output: [1]

解法

考虑到向前进位情况,如果index=0的数字是9,数组长度+1:

class Solution {

public int[] plusOne(int[] digits) {

if (digits.length == 0) {

return new int[]{1};

} else {

for (int i = digits.length - 1; i >= 0; i–) {

if (digits[i] != 9) {

digits[i] += 1;

return digits;

} else {

if (i == 0) {

int[] newDigits = new int[digits.length + 1];

newDigits[0] = 1;

return newDigits;

} else

digits[i] = 0;

}

}

return digits;

}

}

}

67. Add Binary


Given two binary strings, return their sum (also a binary string).

For example,

a = "11"

b = "1"

Return "100".

解法

二进制相加,我的解法比较复杂,应该可以化简为繁。

class Solution {

public String addBinary(String a, String b) {

int aLength = a.trim().length();

int bLength = b.trim().length();

if (aLength == 0 && bLength == 0) return “0”;

if (aLength == 0) return b;

if (bLength == 0) return a;

if (aLength < 10 && bLength < 10)

return Integer.toBinaryString(Integer.valueOf(a, 2) + Integer.valueOf(b, 2));

char[] maxChars, minChars;

int maxLength = 0, minLength = 0;

if (aLength >= bLength) {

maxLength = aLength;

minLength = bLength;

maxChars = a.toCharArray();

minChars = b.toCharArray();

} else {

maxLength = bLength;

minLength = aLength;

maxChars = b.toCharArray();

minChars = a.toCharArray();

}

boolean plusOne = false;

for (int i = 0; i < minLength; i++) {

if (minChars[minLength - 1 - i] == ‘0’ && maxChars[maxLength - 1 - i] == ‘0’) {

maxChars[maxLength - 1 - i] = plusOne ? ‘1’ : ‘0’;

plusOne = false;

} else if ((minChars[minLength - 1 - i] == ‘0’ && maxChars[maxLength - 1 - i] == ‘1’)

|| (minChars[minLength - 1 - i] == ‘1’ && maxChars[maxLength - 1 - i] == ‘0’)) {

maxChars[maxLength - 1 - i] = plusOne ? ‘0’ : ‘1’;

} else {

maxChars[maxLength - 1 - i] = plusOne ? ‘1’ : ‘0’;

plusOne = true;

}

}

if (plusOne) {

if (maxLength == minLength) {

return “1” + new String(maxChars);

} else {

for (int i = 0; i < maxLength - minLength; i++) {

int index = maxLength - minLength - 1 - i;

if (index > 0) {

if (maxChars[index] == ‘0’) {

maxChars[index] = plusOne ? ‘1’ : ‘0’;

plusOne = false;

} else if (maxChars[index] == ‘1’) {

maxChars[index] = plusOne ? ‘0’ : ‘1’;

}

} else {

if (plusOne) {

if (maxChars[0] == ‘0’) {

maxChars[0] = ‘1’;

} else {

maxChars[0] = ‘0’;

return “1” + new String(maxChars);

}

}

}

}

}

}

return new String(maxChars);

}

}

69. Sqrt(x)


求平方根,我最初用的笨方法时间复杂度非常高,超时了:

// Time Limit Exceeded:

class Solution {

public int mySqrt(int x) {

if (x == 0) return 0;

for (int i = 0; i < Integer.MAX_VALUE; i++) {

int product = i * i;

if (product == x) {

return i;

} else if (product > x) {

return i - 1;

}

}

return 0;

}

}

后面考虑到循环参数i的起始值,比如2147483647这个测试用例:

一个循环,每次除以100,直到结果21小于100.

一共除了4次,然后起始值是10的4次方:10000.

然后结果21再去求平方根:4²=16 < 21 < 5²=25,这里取4

所以将10000*4=40000作为起始值,优化后仍然超时。

P.s:

如果21的平方根取4.5呢?或者精确求出sqrt(21)的数值4.58,那么45800和结果46340差距只有540,会不超时吗?

最后在讨论界面看到这个答案:

它的核心是r = (r + x / r) / 2 ,而不是r--

// Accepted

class Solution {

public int mySqrt(int x) {

long r = x;

while (r * r > x)

总结

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上我整理的几十套腾讯、字节跳动,京东,小米,头条、阿里、美团等公司19年的Android面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

技术进阶之路很漫长,一起共勉吧~
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
/ Time Limit Exceeded:

class Solution {

public int mySqrt(int x) {

if (x == 0) return 0;

for (int i = 0; i < Integer.MAX_VALUE; i++) {

int product = i * i;

if (product == x) {

return i;

} else if (product > x) {

return i - 1;

}

}

return 0;

}

}

后面考虑到循环参数i的起始值,比如2147483647这个测试用例:

一个循环,每次除以100,直到结果21小于100.

一共除了4次,然后起始值是10的4次方:10000.

然后结果21再去求平方根:4²=16 < 21 < 5²=25,这里取4

所以将10000*4=40000作为起始值,优化后仍然超时。

P.s:

如果21的平方根取4.5呢?或者精确求出sqrt(21)的数值4.58,那么45800和结果46340差距只有540,会不超时吗?

最后在讨论界面看到这个答案:

它的核心是r = (r + x / r) / 2 ,而不是r--

// Accepted

class Solution {

public int mySqrt(int x) {

long r = x;

while (r * r > x)

总结

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上我整理的几十套腾讯、字节跳动,京东,小米,头条、阿里、美团等公司19年的Android面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

[外链图片转存中…(img-lqDSD2nt-1714934260413)]

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

技术进阶之路很漫长,一起共勉吧~
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 21
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值