1. 两数之和
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize)
{
*returnSize = 2;
int* result = (int*)malloc(sizeof(int) * 2);
for (int i = 0; i < numsSize - 1; i++) {
for (int j = i + 1; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return 0;
}
2. 两数相加
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int c = 0;
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
if (l1 == NULL && l2 == NULL && c == 0) {
return NULL;
}
l1 != NULL ? (c += l1->val, l1 = l1->next) : (c += 0);
l2 != NULL ? (c += l2->val, l2 = l2->next) : (c += 0);
struct ListNode *cur=(struct ListNode *)malloc(sizeof(struct ListNode));
cur->val = c % 10;
c /= 10;
cur->next = addTwoNumbers(l1, l2);
return cur;
}
3. 无重复字符的最长子串
int lengthOfLongestSubstring(char * s)
{
int len = strlen(s);
int fast = 0;
int slow = 0;
int max = 0;
int hash[128] = {0};
while (slow < len && fast < len) {
if (hash[s[fast]] == 0) {
hash[s[fast]] = 1;
fast++;
max = ((fast - slow) > max) ? (fast - slow) : max;
}
else {
hash[s[slow]] = 0;
slow++;
}
}
return max;
}
4. 寻找两个有序数组的中位数
int inc(const void * a, const void *b)
{
return (*(int *)a - *(int *)b);
}
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size)
{
int* nums = (int*)malloc(sizeof(int) * (nums1Size + nums2Size));
int mid = (nums1Size + nums2Size) / 2;
for (int i = 0; i < nums1Size; i++) {
nums[i] = nums1[i];
}
for (int j = 0; j < nums2Size; j++) {
nums[nums1Size + j] = nums2[j];
}
qsort(nums, nums1Size + nums2Size, sizeof(int), inc);
if ((nums1Size + nums2Size) % 2 == 0) {
return (1.0) * (nums[mid - 1] + nums[mid]) / 2;
}
else {
return (1.0) * nums[mid];
}
}
5. 最长回文子串
char * longestPalindrome(char * s)
{
int len = strlen(s);
if (len <= 1) {
return s;
}
int start = 0;
int maxlen = 0;
//i表示中间元素下标
for (int i = 1; i < len; i++)
{
//偶数长度
int low = i - 1;
int high = i;
while (low >= 0 && high < len && s[low] == s[high]) {
low--;
high++;
}
if (high - low - 1 > maxlen) {
maxlen = high - low - 1;
start = low + 1;
}
//奇数长度
low = i - 1; high = i + 1;
while (low >= 0 && high < len && s[low] == s[high]) {
low--;
high++;
}
if (high - low - 1 > maxlen) {
maxlen = high - low - 1;
start = low + 1;
}
}
char *arr = (char *)malloc(sizeof(int) * (maxlen + 1));
int i = 0;
for (; i < maxlen; i++)
{
arr[i] = s[start++];
}
arr[i] = '\0';
return arr;
}