LeetCode的medium题集合(C++实现)三

1 4Sum

Given an array S of n integers, are there elements a,b,c,d in S such that a+b+c+d=target ? Find all unique quadruplets in the array which gives the sum of target.

利用公式a+b=target?c?d 可以将四数和转化为两数和的问题。

vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
    int len= nums.size();
    vector<vector<int> > res;
    vector<int> mid;
    for(int i=0;i<len-3;i++)
    {
       if (i> 0 && nums[i] == nums[i - 1]) continue;
       for(int j=i+1;j<len-2;j++)
       {
           if (j>i+1 && nums[j] == nums[j - 1]) continue;
           int start= j+1, end = len-1,sum=target-nums[i]-nums[j];
           while(start<end)
           {
            if ((nums[start] + nums[end])<sum) start++;
            else if ((nums[start] + nums[end])>sum) end--;
            else
            {
                mid.push_back(nums[i]);
                mid.push_back(nums[j]);
                mid.push_back(nums[start++]);
                mid.push_back(nums[end--]);
                res.push_back(mid);
                mid.clear();
                while (start<end&&nums[start] == nums[start-1]) start++;
                while (start<end&&nums[end] == nums[end+1]) end--;
            }
           }
       }
    }
    return res;
    }

2 Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n=3 , a solution set is:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

该问题可以通过递归解决,使用三个变量分别记录左括号剩余数,右括号剩余数及已使用括号数。当左括号和右括号剩余数都为0时生成一个合法的括号序列。

void generate(int l,int r,vector<char> mid,int count,vector<string>& res)
    {
        if(l<0||r<l) return;
        if(l==0&&r==0)
        {
            string str(mid.begin(),mid.end());
            res.push_back(str);
        }
        else
        {
          if(l>0)
          {
           mid[count]=‘(‘;
           generate(l-1,r,mid,count+1,res);
          }
          if(r>l)
          {
           mid[count]=‘)‘;
           generate(l,r-1,mid,count+1,res);
          }
        }
    }
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        vector<char> mid(2*n,‘\0‘);
        generate(n,n,mid,0,res);
        return res;
    }

3 Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,

Given 1->2->3->4, you should return the list as 2->1->4->3.

同样采用递归的方法,因为每次都是两个相邻节点成对交换,每次递归的头指针为head->next->next, 当head或head->next为空时不用交换。

ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head->next == NULL) return head;
        ListNode *grandChild = swapPairs(head->next->next);
        ListNode *child = head->next;
        child->next = head;
        head->next = grandChild;
        return child;
    }

4 Divide Two Integers

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

为了方便计算先求两个数的绝对值,为了防止溢出将其用long long 类型表示,为了减小时间复杂度,对除数实现成倍数累加。

int divide(int dividend, int divisor) {
    long long count = 0,  result = 0;
    long long sum = 0;
    if (divisor == 0) return  INT_MAX;
    if (dividend == 0)  return 0;
    bool flag = true;
    if ((dividend<0 && divisor>0) || (dividend>0 && divisor<0)) flag = false;
    long long middend=dividend;
    long long midvisor=divisor;
    long long middividend = abs(middend);
    long long middivisor = abs(midvisor);
    while (middividend >= middivisor)
    {
        count = 1;
        sum = middivisor;
        while (sum + sum<=middividend)
        {
            sum += sum;
            count += count;
        }
        middividend -= sum;
        result += count;
    }
    if (!flag) result = -result;
    if(result<INT_MIN||result>INT_MAX) result=INT_MAX;
    return result;
 }
时间: 2024-11-14 12:22:25

LeetCode的medium题集合(C++实现)三的相关文章

LeetCode的medium题集合(C++实现)十一

1 Unique Paths A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked

LeetCode的medium题集合(C++实现)五

1 Combination Sum Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. 可以采用递归的方法解决这个问题,当找到一组数之和

LeetCode的medium题集合(C++实现)六

1 Multiply Strings Given two numbers represented as strings, return multiplication of the numbers as a string.Note: The numbers can be arbitrarily large and are non-negative. 该题实际就是利用字符串来解决大数的乘法问题.为了计算方便先将两组数翻转,将字符串转化为整数利用两个循环逐位相乘,将结果保存.然后逐位解决进位问题. s

LeetCode的medium题集合(C++实现)四

1 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 or

LeetCode的medium题集合(C++实现)十五

1 Subsets Given a set of distinct integers, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,3], a solution is: [ [3], [1],

LeetCode的medium题集合(C++实现)九

1 Jump Game Given an array of non-negative integers, you are initially positioned at the first index of the array.Each element in the array represents your maximum jump length at that position.Determine if you are able to reach the last index. 利用两指针法

LeetCode的medium题集合(C++实现)八

1 Pow(x, n) 该题采用二分法进行递归 double myPow(double x, int n) { if(n==0) return 1; if(n<0) { n=(-n); x=1/x; } double res=myPow(x,n/2); if(n%2==0) { return res*res; } else { return res*res*x; } } 2 Maximum Subarray Find the contiguous subarray within an array

LeetCode的medium题集合(C++实现)十

1 Permutation Sequence The set [1,2,3,-,n] contains a total of n! unique permutations.Given n and k, return the kth permutation sequence. 使用Next Permutation循环k次可以得到序列,但leetcode上提交会出现时间超过限制.下面采用数学法: 在n!个排列中,第一位元素相同的排列总是有(n?1)!个,如果p=k/(n?1)!,那么排列的第一位元素

LeetCode的medium题集合(C++实现)十七

1 Partition List Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.You should preserve the original relative order of the nodes in each of the two partitions.For example: Give