LeetCode刷题第四天 16/20/21题
目录
1. 最接近的三个数之和(LeetCode 16 题)
1.1题目
1.2思路
首先就是三重循环的方法,emmm 这个题和15题有异曲同工之妙。解法也一致。
也是双指针。然后把三个数之和简化为两个数之和。通过双指针不断逼近,然后求得最优解。
1.3代码
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int ans = 10000;
for (int i = 0; i < nums.length-1; i++) {
int j = i+1;
int k = nums.length-1;
while (j<k){
int sumof3 = nums[j] + nums[k] + nums[i];
if (Math.abs( target - sumof3)<Math.abs(target-ans))
ans = sumof3;
if (sumof3<target) j++;
else if(sumof3>target) k--;
else return target;
}
}
return ans;
}
}
2. 有效括号(LeetCode 20 题)
2.1题目
2.2思路
这个题其实思路就是堆栈,只要实现堆栈的操作即可。我自己想的方法还是不够完美。
简述一下我自己的方法,就是首先构建{}[]()的哈希表,然后同过哈希表的值计算是否符合,原理很简单,如果相加为30 说明是匹配括号,同时注意方向,新插入栈的值余数为9。因此需要外加判断,非常麻烦。如果括号相匹配,做出栈操作。这个整体的时间复杂度是N,空间复杂度也是N。
if (s.length()%2!=0) return false;
HashMap<Character, Integer> map = new HashMap<>();
map.put('[', 11);
map.put(']', 19);
map.put('(', 21);
map.put(')', 9);
map.put('{', 1);
map.put('}', 29);
String zhan = "";
char last;
for (int i = 0; i < s.length(); i++) {
if (zhan.length()==0){
zhan+= s.charAt(i);
continue;
}
last = zhan.charAt(zhan.length()-1);
// System.out.println(map.get(last)+" "+s.charAt(i));
int key = map.get(last)+map.get(s.charAt(i));
if (key==30){
if(map.get(s.charAt(i))%10==1) return false;
if (zhan.length()==1){
zhan = "";
continue;
}
zhan = zhan.substring(0,zhan.length()-1);
}else if (key%10==0) return false;
else zhan+=s.charAt(i);
}
if (zhan.length()==0) return true;
else return false;
然后大佬的思路就是把我的字符串栈换成了真正的栈,然后把我的harshmap换成了条件表达式。我确实没人家写的言简意赅。
2.3代码
class Solution {
public boolean isValid(String s) {
Stack<Character>stack = new Stack<Character>();
for(char c: s.toCharArray()){
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();
}
}
3. 合并两个有序链表(LeetCode 21 题)
3.1题目
3.2思路
比较呆的方法就是把链表整体排序,然后再装入新的链表。时间复杂度为N2
相对理想的方法就是对链表进行遍历,首先创建新链表,然后l1和l2逐个进行比较,当l1大于l2 进行拼接,当遍历完其中一个链表跳出循环,把剩下一个的剩余部分拼接即可。
3.3代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode resout = new ListNode(0);
ListNode ans =resout;
while (l1!=null&&l2!=null){
if (l1.val<=l2.val){
resout.next = l1;
resout = resout.next;
l1 = l1.next;
}else {
resout.next = l2;
resout = resout.next;
l2= l2.next;
}
}
if (l1==null){
resout.next = l2;
} else {
resout.next = l1;
}
return ans.next;
}
}
4.总结
今天的题不太难,也是因为前面的学习给自己一定的积累。每天都坚持下来进步看到眼里。希望每个刷力扣的人都可以坚持下来,勉励自己继续加油。