腾讯精选练习 50 题 Day4
题目:16. 最接近的三数之和
来源:力扣(LeetCode) https://leetcode-cn.com/problems/3sum-closest/
【中等难度】给定一个包括 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
解题思路
与15题方法几乎一模一样
执行代码
class Solution {
public int threeSumClosest(int[] nums, int target) {
int len = nums.length;
int min_dis = Integer.MAX_VALUE;
int result = 0;
Arrays.sort(nums); // 排序
for (int i = 0; i < len-2 ; i++) {
int L = i+1;
int R = len-1;
while(L < R){
int sum = target - nums[i] - nums[L] - nums[R];
if(Math.abs(sum)<min_dis){
min_dis = Math.abs(sum);
result = target - sum;
}
else if (sum == 0) return target;
else if (sum > 0) L++;
else if (sum < 0) R--;
}
}
return result;
}
}
复杂度
时间复杂度:O(n^2)
空间复杂度:O(1)
题目:20. 有效的括号
来源:力扣(LeetCode)https://leetcode-cn.com/problems/valid-parentheses/
简单的堆栈运用,故不写题解。
题目21. 合并两个有序链表
https://leetcode-cn.com/problems/merge-two-sorted-lists/
【简单难度】将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列
思路
1、关键是要把对比的流程、指针移动的流程搞清楚,故需画图。
2、需要定义两个新节点,一个为头结点、一个为遍历的节点。
3、细节:为头结点赋值,可使后续操作统一。
下图解转载自leetCode.
执行代码
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null&&l2==null) return null;
ListNode head = new ListNode(0);
ListNode temp = head;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
temp.next = l1;
l1 = l1.next;
temp = temp.next;
}else if(l1.val>l2.val){
temp.next = l2;
l2 = l2.next;
temp = temp.next;
}
}
temp.next = l1==null?l2:l1;
return head.next;
}
}
复杂度
时间复杂度:O(n+m)
空间复杂度:O(1)