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;
}
}
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;
}
}
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;
}
}
The count-and-say sequence is the sequence of integers with the first five terms as following:
-
1
-
11
-
21
-
1211
-
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;
}
}
}
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;
}
}
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;
}
}
}
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;
}
}
}
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);
}
}
求平方根,我最初用的笨方法时间复杂度非常高,超时了:
// 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)
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
![](https://i-blog.csdnimg.cn/blog_migrate/b67753139c4d19ee88ded2ec80f33be4.jpeg)
最后
其实Android开发的知识点就那么多,面试问来问去还是那么点东西。所以面试没有其他的诀窍,只看你对这些知识点准备的充分程度。so,出去面试时先看看自己复习到了哪个阶段就好。
上面分享的腾讯、头条、阿里、美团、字节跳动等公司2019-2021年的高频面试题,博主还把这些技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,上面只是以图片的形式给大家展示一部分。
【Android思维脑图(技能树)】
知识不体系?这里还有整理出来的Android进阶学习的思维脑图,给大家参考一个方向。
【Android高级架构视频学习资源】
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!
int x) {
long r = x;
while (r * r > x)
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-8IEk7ssK-1713392423939)]
[外链图片转存中…(img-R1cUuaVO-1713392423941)]
[外链图片转存中…(img-mMpnL67x-1713392423942)]
[外链图片转存中…(img-XjR823sG-1713392423943)]
[外链图片转存中…(img-mgls1sXU-1713392423944)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)
![](https://i-blog.csdnimg.cn/blog_migrate/b67753139c4d19ee88ded2ec80f33be4.jpeg)
最后
其实Android开发的知识点就那么多,面试问来问去还是那么点东西。所以面试没有其他的诀窍,只看你对这些知识点准备的充分程度。so,出去面试时先看看自己复习到了哪个阶段就好。
上面分享的腾讯、头条、阿里、美团、字节跳动等公司2019-2021年的高频面试题,博主还把这些技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节,由于篇幅有限,上面只是以图片的形式给大家展示一部分。
【Android思维脑图(技能树)】
知识不体系?这里还有整理出来的Android进阶学习的思维脑图,给大家参考一个方向。
[外链图片转存中…(img-KFPSC3Br-1713392423946)]
【Android高级架构视频学习资源】
《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!