leetcode 题解代码整理 1-5题

Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

题意:给出一串数字,求下标最小的两个数字和等于target,返回下标,要求index1<index2

思路:先把数据按大小排序,i指向最左,last指向最右,若相加<target则i++,否则last--

class Solution
{
public:
    vector<int> twoSum(vector<int>& nums, int target)
    {
        pair<int,int>a,b;
        vector<pair<int,int>>mark;
        for (int i=0;i<nums.size();i++)
        {
            b={nums[i],i+1};
            mark.push_back(b);
        }
        sort(mark.begin(),mark.end());
        int last=mark.size()-1;

        for (int i=0;i<last;)
        if (mark[i].first+mark[last].first==target)
        {
            b={min(mark[i].second,mark[last].second),max(mark[i].second,mark[last].second)};
            break;
        }
        else
        if (mark[i].first+mark[last].first<target)
            i++;
        else
            last--;

        vector<int>ans;
        ans.push_back(b.first);
        ans.push_back(b.second);

        return ans;
    }
};

Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

题意:给出两个链表,输出两个链表的和,链表的每一位只存储一位,若进位则进位到下个链表结点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
    {
        ListNode *e,*ans,*mark;
        int t=0;
        ans=(ListNode*)malloc(sizeof(ListNode));
        mark=ans;
        while (l1!=NULL || l2!=NULL)
        {
            if (l1!=NULL && l2!=NULL)
            {
                e=(ListNode*)malloc(sizeof(ListNode));
                *e=ListNode((l1->val+l2->val+t)%10);
                t=(l1->val+l2->val+t)/10;

                l1=l1->next;
                l2=l2->next;
                mark->next=e;
                mark=mark->next;
            }
            if (l1==NULL && l2!=NULL)
            {
                e=(ListNode*)malloc(sizeof(ListNode));
                *e=ListNode((l2->val+t)%10);
                t=(l2->val+t)/10;

                l2=l2->next;
                mark->next=e;
                mark=mark->next;
            }
            if (l1!=NULL && l2==NULL)
            {
                e=(ListNode*)malloc(sizeof(ListNode));
                *e=ListNode((l1->val+t)%10);
                t=(l1->val+t)/10;

                l1=l1->next;
                mark->next=e;
                mark=mark->next;
            }
        }

        if (t!=0)
        {
            e=(ListNode*)malloc(sizeof(ListNode));
            *e=ListNode(t);
            mark->next=e;
        }

        return ans->next;

    }
};

Longest Substring Without Repeating Characters

Given
a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

题意:找出最长连续字串,保证每个字母最多只出现一次

思路:用last标记上一个可用的起始位置,x数组标记每个字母上一次出现的位置,从做到右遍历一遍,每次取最右的可用起始位置

class Solution
{
public:
    int lengthOfLongestSubstring(string s)
    {

        int x[220],last=-1,ans=0;
        memset(x,-1,sizeof(x));
        for (int i=0;i<s.size();i++)
        {
            if (x[s[i]]>last) last=x[s[i]];
            if (i-last>ans) ans=i-last;
            x[s[i]]=i;
        }
        return ans;

    }
};

Median of Two Sorted Arrays

There
are two sorted arrays nums1 and nums2 of
size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

题意:给出两个序列,找出两个序列合并起来的中位数,要求时间复杂度log(n+m)

思路:将问题转换为找两个序列合并起来的第K小数,找第K小数,可以把K平分到A,B两个序列中,如果A[k/2-1]<B[k/2-1],那么A[0]~A[k/2-1]一定在第k小的数的序列当中,则去掉这部分,直到K==1,。

class Solution
{

public:
    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
    {

        int a[1010],b[1010];
        m=nums1.size();
        for (int i=0;i<m;i++)
        a[i]=nums1[i];
        n=nums2.size();
        for (int i=0;i<n;i++)
        b[i]=nums2[i];
        if ((n+m)%2==1)
            return find(a,m,b,n,(n+m)/2+1);
        else
            return (find(a,m,b,n,(n+m)/2)+find(a,m,b,n,(n+m)/2+1))/2;
    }

private:
int n,m;
    double find(int a[],int m,int b[],int n,int k)
    {
        if (m>n)
            return find(b,n,a,m,k);
        if (m==0)
            return b[k-1];
        if (k==1)
            return min(a[0],b[0]);
        int pa=min(k/2,m),pb=k-pa;
        if (a[pa-1]<b[pb-1])
            return find(a+pa,m-pa,b,n,k-pa);
        else
        if (a[pa-1]>b[pb-1])
            return find(a,m,b+pb,n-pb,k-pb);
        else
            return a[pa-1];

    }

};

Longest Palindromic Substring

Given
a string S,
find the longest palindromic substring in S.
You may assume that the maximum length of S is
1000, and there exists one unique longest palindromic substring.

题意:求长度为1000的最长回文子串

思路:n*n复杂度区间DP,其他算法以后再实现。。。。

class Solution
{
public:
    string longestPalindrome(string s)
    {
        int len=s.length(),mx=1,start=0;
        int flag[len][len];
        for (int i=0;i<len;i++)
            for (int j=0;j<len;j++)
            if (i>=j)
                flag[i][j]=1;
            else
                flag[i][j]=0;

        for (int i=2;i<=len;i++)
            for (int j=0;j<len-i+1;j++)
            {
                int k;
                k=i+j-1;
                if (s[j]==s[k])
                    flag[j][k]=flag[j+1][k-1];

                if (flag[j][k]==1 && mx<i)
                    {
                        mx=i;
                        start=j;
                    }

            }

        return s.substr(start,mx);

    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-12-24 08:30:33

leetcode 题解代码整理 1-5题的相关文章

leetcode 题解代码整理 36-40题

Valid Sudoku Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. A partially filled sudoku which is valid. 判断数独当前状态是否合法 class Solut

leetcode 题解代码整理 31-35题

Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending orde

leetcode 题解代码整理 21-25题

Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 合并两个有序链表 /** * Definition for singly-linked list. * struct ListNode { * int val; * Li

leetcode 题解代码整理 6-10题

ZigZag Conversion The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line

【题解整理】二分题

[题解整理]二分题 题目类型: 二分查找: 二分答案. 大致解题思路: 查找注意有序和返回值: 浮点数注意精度: 整数注意返回值,建议另外维护一个变量,用于储存可行解. 题目 分类 传送门 WA点 poj 2785 二分查找 题解 lightoj 1088 二分查找 题解 lightoj 1307 二分查找 题解 longlong poj 2456 整数二分答案 题解 poj 3104 整数二分答案 题解 poj 3258 整数二分答案 题解 poj 3273 整数二分答案 题解 lightoj

【LeetCode】树(共94题)

[94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 - n 的所有形态的BST. 题解:枚举每个根节点 r, 然后递归的生成左右子树的所有集合,然后做笛卡尔积. 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *

[LeetCode]题解(python):031-Next Permutation

题目来源 https://leetcode.com/problems/next-permutation/ Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible

[LeetCode 题解]: Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3}, 1 2 / 3 return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? 题意 先序遍历二叉树,递归的思路是普通的,能否用迭代呢? 非递归思路:<借助stack>

leetcode题解:Search in Rotated Sorted Array(旋转排序数组查找)

题目: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no du