剑指offer四月第一周刷题记录
今天晚上看到一个大佬写的有关于OCR(文本识别技术)的一篇帖子,这个大佬码龄7年,写了349篇贴,差不多每周一篇帖子,和我的打算一样,十年磨一剑,他能用七年攒粉3万+。我不知道自己能在技术上学到什么程度,但我这周给自己的任务却没有完成。在此狠狠的鞭笞一下自己,骂自己两句。不能放弃,给自己留下三年的时间再提升一下自己,年轻是资本,是因为自己还可以努力,还可以再尽全力去拼一下自己所向往的东西,如果年轻而不努力,那终将无法成为资本。
一、简单题(四道)
(一)
剑指offer 7 :
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
解答思路:得出每一位的数值,例如,个位取值=x%10,十位取值=(x-个位取值)/10,依次类推。然后进行反转,结果数=各位取值对应的数值乘积。然后进行思路优化,每次取值都以10为规模,进行反转。
解答代码:
class Solution {
public int reverse(int x) {
long n = 0 ;
while(x != 0){
n=n*10+x%10;
x=x/10;
}
return (int)n==n?(int)n:0;
}
}
**剑指offer 14 :**最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入:strs = [“flower”,“flow”,“flight”]
输出:“fl”
示例 2:
输入:strs = [“dog”,“racecar”,“car”]
输出:""
解释:输入不存在公共前缀。
解答思路*:设置哨兵,以第一个字符串为起点,依次与其后的字符串比较,如果出现不以第一个字符串的前缀为前缀的字符串,则这个前缀不为公共前缀,以这个前缀减去一个字符作为公共前缀,循环遍历。
代码:
class Solution {
public String longestCommonPrefix(String[] strs) {
String res="";
if(strs.length==0)
return res;
if(strs.length==1)
return strs[0];
res=strs[0];
for(int i=1;i<strs.length;i++)
{
while(!strs[i].startsWith(res)){
res=res.substring(0,res.length()-1);
if(res.length()==0)
return "";
}
}
return res;
}
}
二、中等题
剑指offer 148题
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
class Solution {
public ListNode sortList(ListNode head) {
return sortList(head, null);
}
public ListNode sortList(ListNode head, ListNode tail) {
if (head == null) {
return head;
}
if (head.next == tail) {
head.next = null;
return head;
}
ListNode slow = head, fast = head;
while (fast != tail) {
slow = slow.next;
fast = fast.next;
if (fast != tail) {
fast = fast.next;
}
}
ListNode mid = slow;
ListNode list1 = sortList(head, mid);
ListNode list2 = sortList(mid, tail);
ListNode sorted = merge(list1, list2);
return sorted;
}
public ListNode merge(ListNode head1, ListNode head2) {
ListNode dummyHead = new ListNode(0);
ListNode temp = dummyHead, temp1 = head1, temp2 = head2;
while (temp1 != null && temp2 != null) {
if (temp1.val <= temp2.val) {
temp.next = temp1;
temp1 = temp1.next;
} else {
temp.next = temp2;
temp2 = temp2.next;
}
temp = temp.next;
}
if (temp1 != null) {
temp.next = temp1;
} else if (temp2 != null) {
temp.next = temp2;
}
return dummyHead.next;
}
}
## 三、复杂题