1.两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
2. 两数相加
给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
struct ListNode* head = nullptr, * tail = nullptr;
int carry = 0;
while(l1 || l2)
{
int n1 = l1 ? l1->val : 0;
int n2 = l2 ? l2->val : 0;
int sum = n1 + n2 + carry;
if(!head)
{
head = tail = new ListNode(sum%10);
//tail->next = nullptr;
}
else
{
tail->next = new ListNode(sum%10);
tail = tail->next;
//tail->next = nullptr;
}
carry = sum/10;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
}
if(carry>0)
{
tail->next = new ListNode(1);
tail = tail->next;
}
return head;
}
};
3. 无重复字符的最长子串
给定一个字符串 s
,请你找出其中不含有重复字符的 最长子串 的长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> occ;
int n = s.size();
int rk = 0, ans = 0;
for(int i=0; i<n; ++i)
{
while(rk<n && !occ.count(s[rk]))
{
occ.insert(s[rk]);
++rk;
}
ans = max(ans,rk-i);
occ.erase(s[i]);
}
return ans;
}
};
4.寻找两个正序数组的中位数
给定两个大小分别为 m
和 n
的正序(从小到大)数组 nums1
和 nums2
。请你找出并返回这两个正序数组的 中位数 。
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
int i=0, j=0, k=0, mid;
double ret, ret2;
if( (nums1Size==0) && (nums2Size==1) ) //情况1
return nums2[0];
else if( (nums1Size==1) && (nums2Size==0) ) //情况2
return nums1[0];
if( (nums1Size + nums2Size)>=2 ) //情况3;注意这里是大于等于2,包括了[][1,2]情况;
{
mid = (nums1Size + nums2Size) / 2;
while(i<=mid)
{
ret2=ret;
if( j<nums1Size && k<nums2Size)
ret = nums1[j]<nums2[k] ? nums1[j++] : nums2[k++];
else if( j >= nums1Size)
ret = nums2[k++];
else if( k >= nums2Size)
ret = nums1[j++];
i++;
}
if( (nums1Size + nums2Size) % 2 == 0 ) //若总数目为偶数;
ret = (ret+ret2)/2;
}
return ret;
}