2.两数相加
题目描述:给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头
思路:将两个链表表示的数字按照数学中两数相加的规则:小于等于九直接写入新链表对应位置,大于九向后进一位。依次计算到最后一位。
代码如下:
/**
* 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 AddTwoNumbers(ListNode l1, ListNode l2) {
ListNode lp = new ListNode(0,new ListNode());
ListNode l = lp;
while (l1.next != null || l2.next != null)
{
if (l1.next == null)
l1.next = new ListNode();
if (l2.next == null)
l2.next = new ListNode();
int temp = l1.val + l2.val + l.val;
if (temp > 9)
{
l.val = temp%10;
l.next = new ListNode(temp/10,new ListNode());
l=l.next;
}
else
{
l.val = temp;
l = l.next;
l.next = new ListNode();
}
*l1 = l1.next;
l2 = l2.next;
}
if (l1 == null)
l1.val = 0;
if (l2 == null)
l2.val = 0;
l.val += l1.val + l2.val;
if (l.val > 9)
{
l.next.val = l.val/10;*
l.val=l.val%10;
}
else
l.next = null;
return lp;
}
}
4.寻找两个正序数组的中位数
题目描述:给定两个大小为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的中位数。
思路:1.直接将两个数组合并成一个数组进行排序后找出中位数。
代码如下:
public class Solution {
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
int len1 = nums1.Length;
int len2 = nums2.Length;
int[] nums=new int[len1+len2];
for (int i = 0; i < len1; i++)
nums[i] = nums1[i];
for (int i = len1; i < len1 + len2; i++)
nums[i] = nums2[i-len1];
Array.Sort(nums);
if ((len1 + len2) % 2 == 0)
return (double)(nums[(len1 + len2) / 2 - 1] + nums[(len1 + len2) / 2]) / 2;
else
return nums[(len1 + len2) / 2];
}
}
思路:2.利用二分法找到nums1中存在于“|”左边的最大元素(利用“|”左边元素一定小于等于右边为原理),“|”左边剩余元素由nums2中靠前的元素补充,将两个数组的元素分别存放到“|”的两边,使中位数在“|”的两边产生。
代码如下:
public class Solution {
public double FindMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.Length;
int n = nums2.Length;
if(m>n)
return FindMedianSortedArrays(nums2, nums1);
int k = (m + n+1) / 2;
int left=0;
int right=m;
while (left < right)
{
int t = (left + right) / 2;
if (nums1[t] < nums2[k - t - 1])
left = t + 1;
else
right=t;
}
int k1 = left;
int k2=k-right;
int a1 = Math.Max(k1 == 0 ? int.MinValue : nums1[k1 - 1], k2 == 0 ? int.MinValue : nums2[k2 - 1]);
if ((m + n) % 2 != 0)
return a1;
else
{
int a2 = Math.Min(k1 == m ? int.MaxValue : nums1[k1], k2 == n ? int.MaxValue : nums2[k2]);
return (double)(a1 + a2) / 2;
}
}
}
5.最长回文子串
题目描述:给你一个字符串 s,找到 s 中最长的回文子串。
思路:利用动态规划的思想,利用一个bool类型的二维数组将能构成回文串的子串进行标记(行标表示回文子串的起点,列标表示回文子串的终点),对每个子串进行遍历,最终得到最长的回文子串。
代码如下:
public class Solution {
public string LongestPalindrome(string s) {
if (s.Length <= 1)
return s;
int len = s.Length;
bool[,] yn = new bool[len, len];
int templen = 1;
string temps = s.Substring(0, 1);
for (int i = 1; i < len; i++)
{
for (int j = 0; j < i; j++)
{
if (s[i] == s[j] && (yn[j + 1, i - 1] == true || i - j <= 2))
{
yn[j, i] = true;
if (i - j + 1 > templen)
{
templen = i - j + 1;
temps = s.Substring(j, i - j + 1);
}
}
}
}
return temps;
}
}