Leetcode(7) - medium1

11, 16, 24, 39, 43, 50, 69

11.Container With Most Water My Submissions Question
Given n non-negative integers a1, a2, …, an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.

题意是给定一个高度的数组作为隔板的高度,求数组中任意两隔板间盛水的最大容积,显然:隔板间的距离与较低隔板的高度乘积即为盛水的容量。

class Solution {
public:
    int maxArea(vector<int> &height) 
    {
        int capability = 0;
        int left = 0, right = height.size() - 1;    
        int water = 0;
        while (left < right)
        {
            //隔板间的距离与较低隔板的高度乘积即为盛水的容量
            water = min(height[left], height[right]) * (right - left);
            //更新最值
            if (water > capability) capability = water;
            //移动指针从较小的边开始收缩
            if (height[left] < height[right])
                ++left;
            else
                --right;
        }

        return capability;
    }
};

16.3Sum Closest My Submissions Question
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
求解如下:
思路与3sum一样,也是仿3重循环遍历

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        int n = nums.size();
        sort(nums.begin(), nums.end());
        int ret,sum;
        //初始化
        sum = nums[0]+nums[1]+nums[n-1];
        ret = sum;
        int i,j,k;
        for(i=0; i<n; i++){
            j=i+1; k=n-1;
            while(j<k){
                sum = nums[i]+nums[j]+nums[k];
                if (abs(sum - target) < abs(ret - target))
                    ret = sum;                                         
                if (ret == target)
                    return ret;
                if(sum - target>0)
                    //大于0,说明需要减小,所以第三个数往左移
                    k--;
                else
                    //小于0,说明需要增大,所以第二个数往右移。
                    j++;
            }
        }
        return ret;
    }
};

24.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.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
   ListNode* swapPairs(ListNode* head) {
        if(head==NULL || head->next==NULL) return head;
        else{
            ListNode* cur = head;
            int temp;
            ListNode* p=head;            
            temp=cur->next->val;
            cur->next->val=cur->val;
            cur->val=temp;
            swapPairs(p->next->next);
            return head;
        }       
    }  
};

39.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.
可重复使用无法按3sum那样循环,否则会超时
将问题看作树的搜索问题,显然是DFS算法
注意结果需要从小到大排序。

class Solution {
public:
    vector<vector<int>>res;
    vector<int>ans;
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        if(candidates.empty()) return res;
        dfs(0, 0, target, candidates);
        //排序结果
        for(int i=0; i<res.size(); i++)
            sort(res[i].begin(),res[i].end());
        return res;
    }
    void dfs(int start, int sum, int target,vector<int> candidates){
        if(sum == target){
            res.push_back(ans);
            return;
        }
        else if(sum > target)
            return;
        else{
            for(int i = start; i < candidates.size(); i++){
                ans.push_back(candidates[i]);
                dfs(i, sum + candidates[i], target, candidates);
                ans.pop_back();
            }
        }

    }
};

43.Multiply Strings My Submissions Question
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.
大数字乘法,首先考虑模拟手工计算
各位相乘,进位。。好麻烦,搁置一下

class Solution {
public:
    string multiply(string num1, string num2) {


    }
};

50.Pow(x, n)
剑P93
刚好在树上看到这个题目,难点在于n为0或者负数的处理

class Solution {
public:
    double Power(double base, int exponent) {
        if(exponent==0) return 1;
        if(base==0) return 0;
        //负数处理
        if(exponent<0){
            exponent=-exponent;
            base=1.0/base;
        }
        double res = 1.0;
        //位运算
        while(exponent){
            //如果是奇数
            if(exponent&1) res=res*base;
            base=base*base;
            //右移一位
            exponent=exponent>>1;
        }
        return res;
    }
};

69.Sqrt(x)
同样是二分查找

class Solution {
public:
    int mySqrt(int x) {
        if (x < 0)  return -1;
        if (x == 0) return 0; 
        //注意与一般二分初始化不同        
        int low = 1; 
        int high = x / 2 + 1; 
        int mid;        
        while (low <= high) {            
            mid = (high + low)/ 2;
            //避免过分迭代           
            if ((x / mid >= mid) && ((mid + 1) > x / (mid + 1))) { 
                return mid; 
            } else if ( x / mid < mid ) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }            
        }
        return -1;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Leetcode题库是一个包含了各种算法和数据结构问题的在线题库,供程序员练习和提升技能使用。这个题库中涵盖了大量的题目,包括但不限于图遍历、最短路径、有效的括号、字符串解码、Z字形变换、最长公共前缀、字符串相乘、颠倒字符串中的单词、比较版本号、反转字符串、压缩字符串、验证IP地址等等。它提供了java实现的leetcode解法,这些解法的代码规范,可读性良好,并且其中的解法思想并不受语言限制。通过解决这些题目,程序员可以提高自己的算法和编码能力。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [leetcode题库-leetcode-java:LeetcodeJava代码](https://download.csdn.net/download/weixin_38661100/19901136)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [LeetCode算法题整理(200题左右)](https://blog.csdn.net/qq_38253797/article/details/126827454)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值