LeetCode题解(一)0001-0099,专题解析

###解法:

class Solution {

public int romanToInt(String s) {

int total = 0;

if (s.indexOf(“IV”) != -1) total -= 2;

if (s.indexOf(“IX”) != -1) total -= 2;

if (s.indexOf(“XL”) != -1) total -= 20;

if (s.indexOf(“XC”) != -1) total -= 20;

if (s.indexOf(“CD”) != -1) total -= 200;

if (s.indexOf(“CM”) != -1) total -= 200;

char[] charArray = s.toCharArray();

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

switch (charArray[i]) {

case ‘I’:

total += 1;

break;

case ‘V’:

total += 5;

break;

case ‘X’:

total += 10;

break;

case ‘L’:

total += 50;

break;

case ‘C’:

total += 100;

break;

case ‘D’:

total += 500;

break;

case ‘M’:

total += 1000;

break;

}

}

return total;

}

}

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;

}

}

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
img

最后

我一直以来都有整理练习大厂面试题的习惯,有随时跳出舒服圈的准备,也许求职者已经很满意现在的工作,薪酬,觉得习惯而且安逸。

不过如果公司突然倒闭,或者部门被裁减,还能找到这样或者更好的工作吗?

我建议各位,多刷刷面试题,知道最新的技术,每三个月可以去面试一两家公司,因为你已经有不错的工作了,所以可以带着轻松的心态去面试,同时也可以增加面试的经验。

我可以将最近整理的一线互联网公司面试真题+解析分享给大家,大概花了三个月的时间整理2246页,帮助大家学习进步。

由于篇幅限制,文档的详解资料太全面,细节内容太多,所以只把部分知识点截图出来粗略的介绍,每个小节点里面都有更细化的内容!以下是部分内容截图:

部分目录截图

中…(img-NhF56Dy5-1711658211994)]
[外链图片转存中…(img-JqxfECEE-1711658211995)]
[外链图片转存中…(img-Zlk8Cg4G-1711658211995)]
[外链图片转存中…(img-lm6RLFwe-1711658211996)]
[外链图片转存中…(img-V0JqbClX-1711658211996)]
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
[外链图片转存中…(img-Lu4OGeWe-1711658211997)]

最后

我一直以来都有整理练习大厂面试题的习惯,有随时跳出舒服圈的准备,也许求职者已经很满意现在的工作,薪酬,觉得习惯而且安逸。

不过如果公司突然倒闭,或者部门被裁减,还能找到这样或者更好的工作吗?

我建议各位,多刷刷面试题,知道最新的技术,每三个月可以去面试一两家公司,因为你已经有不错的工作了,所以可以带着轻松的心态去面试,同时也可以增加面试的经验。

我可以将最近整理的一线互联网公司面试真题+解析分享给大家,大概花了三个月的时间整理2246页,帮助大家学习进步。

由于篇幅限制,文档的详解资料太全面,细节内容太多,所以只把部分知识点截图出来粗略的介绍,每个小节点里面都有更细化的内容!以下是部分内容截图:

[外链图片转存中…(img-j7CfXhP8-1711658211997)]

[外链图片转存中…(img-adelfemr-1711658211997)]

本文已被CODING开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》收录

  • 15
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值