16.最接近的三数之和
题目描述:给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
思路:根据第十五题的思路,使用三个索引的方法对数组进行遍历,找到最优解答。
代码如下:
public class Solution
{
public int ThreeSumClosest(int[] nums, int target)
{
int temp = 0;
int min = int.MaxValue;
int tt = 0;
int result = 0;
Array.Sort(nums);
for (int i = 0; i < nums.Length-2; i++)
{
int l = i + 1;
int r = nums.Length - 1;
while (l < r)
{
if (nums[i] + nums[l] + nums[r] == target)
return target;
else if (nums[i] + nums[l] + nums[r] < target)
{
tt = nums[i] + nums[l] + nums[r];
temp = Math.Abs(tt - target);
l++;
}
else
{
tt = nums[i] + nums[l] + nums[r];
temp = Math.Abs(tt - target);
r--;
}
if (min > temp)
{
result=tt;
min = temp;
}
}
}
return result;
}
}
20.有效括号
题目描述:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 注意空字符串可被认为是有效字符串。
思路:利用栈,如果遇到左括号,像栈中加入对应的右括号,如果遇到右括号,就将它与栈中第一个元素比较,通过全部比较下来,可以得出是否是有效括号。
代码如下:
public class Solution
{
public bool IsValid(string s)
{
if (string.IsNullOrEmpty(s))
return true;
Stack<char> mystack = new Stack<char>();
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '(')
mystack.Push(')');
else if (s[i] == '[')
mystack.Push(']');
else if (s[i] == '{')
mystack.Push('}');
else
{
if (mystack.Count==0||mystack.Pop() != s[i])
return false;
}
}
return mystack.Count == 0;
}
}
21.合并两个有序链表
*题目描述:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 *

思路:先构建一个新的链表,分别比较两个链表的头节点,将较小的放入新链表,头节点向后移动,直到得到新链表。
代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution
{
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
ListNode p = new ListNode();
ListNode temp = p;
while (l1 != null && l2 != null)
{
if (l1.val > l2.val)
{
temp.next = l2;
l2 = l2.next;
}
else
{
temp.next = l1;
l1 = l1.next;
}
temp = temp.next;
}
if (l1 == null)
temp.next = l2;
if (l2 == null)
temp.next = l1;
return p.next;
}
}
算法解析:三数之和、有效括号与链表合并
这篇博客探讨了三种不同的编程问题:寻找数组中和最接近目标值的三个数、判断字符串是否为有效括号组合以及如何合并两个有序链表。针对每个问题,博主提供了详细的解决方案,包括使用排序、双指针和栈等数据结构,展示了在算法和数据结构上的应用技巧。
105

被折叠的 条评论
为什么被折叠?



