Leetcode Task04:完成16、20、21题目并打卡
016 三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和
。假定每组输入只存在唯一答案。
示例:
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
提示:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int min_sum = Integer.MAX_VALUE,min_distance = Integer.MAX_VALUE;
for(int i = 0; i < nums.length - 2;i++){
int low = i + 1,high = nums.length - 1;
while(low < high){
int sum = nums[i] + nums[low] + nums[high];
if(Math.abs(sum - target) <min_distance){
min_sum = sum;
min_distance = Math.abs(sum - target);
}
if(sum > target){
high--;
}else{
low++;
}
}
}
return min_sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
020 括号匹配
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
//leetcode submit region begin(Prohibit modification and deletion)
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++) {
Character character1 = s.charAt(i);
if(character1 == '(' || character1 == '[' || character1 == '{') {
stack.push(character1);
}else if(character1 == ')') {
if(stack.isEmpty()) {
return false;
}
Character character2 = stack.pop();
if(character2 != '(') {
return false;
}
}else if(character1 == ']') {
if(stack.isEmpty()) {
return false;
}
Character character2 = stack.pop();
if(character2 != '[') {
return false;
}
}else if(character1 == '}') {
if(stack.isEmpty()) {
return false;
}
Character character2 = stack.pop();
if(character2 != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
//leetcode submit region end(Prohibit modification and deletion)
021 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列
//leetcode submit region begin(Prohibit modification and deletion)
/**
* 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 l3 = new ListNode(-1);
ListNode dummy = l3;
while(l1!=null && l2 != null){
if(l1.val < l2.val){
dummy.next = l1;
dummy = l1;
l1 = l1.next;
}else{
dummy.next = l2;
dummy = l2;
l2 = l2.next;
}
}
if(l1 == null){
l1 = l2;
}
dummy.next = l1;
return l3.next;
}
}
//leetcode submit region end(Prohibit modification and deletion)

浙公网安备 33010602011771号