Two Sum - Input array is sorted

在已排序的整数数组中寻找两个数使它们相加等于特定目标值。本题要求返回这两个数的下标,且下标从1开始计数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given an array of integers that is already sorted in ascending order, 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.

样例

Given nums = [2, 7, 11, 15], target = 9

return [1, 2]

解题思路:暴力剪枝,水过。。。。没有考虑负数情况,所以首先进行一次筛选,然后直接枚举出答案即可。

解题代码:

class Solution {
public:
    /*
     * @param numbers : An array of Integer
     * @param target : target = numbers[index1] + numbers[index2]
     * @return : [index1+1, index2+1] (index1 < index2)
     */
    vector<int> twoSum(vector<int> &nums, int target) {
        // write your code here
        vector<int>tem;
        map<int,int>tem1;
        for(int i=0;i<nums.size();i++){
            if(nums[i]<target){
                tem.push_back(nums[i]);
                tem1[nums[i]]=i;
            }
        }
        vector<int> ans;
        for(int i=0;i<tem.size();i++){
            for(int j=i+1;j<tem.size();j++){
                if(tem[i]+tem[j]==target){
                    ans.push_back(tem1[tem[i]]+1);
                    ans.push_back(tem1[tem[j]]+1);
                    return ans;
                }
            }
        }
    }
};


内容概要:本文详细介绍了C#编程语言的学习资源,涵盖了从基础到高级的不同层次。首先,对于初学者,推荐了多本经典书籍如《C# 8.0 and .NET Core 3.0 - Modern Cross-Platform Development》、《C# 9.0 in a Nutshell》等,以及在线课程和视频教程,帮助理解C#的基本语法、面向对象编程等概念。接着,针对进阶开发者,提供了深入研究C#特性的书籍和课程,如《C# 9 and .NET 5 – Modern Cross-Platform Development》,并推荐了一些实战项目来巩固所学知识。最后,为高级开发者准备了深入探讨C#内部机制和技术细节的书籍,如《CLR via C#》,以及高级课程和开源项目。此外,还介绍了常用的开发工具(如Visual Studio、Visual Studio Code)、框架(如ASP.NET Core、Entity Framework Core),并列出了活跃的开发社区和论坛供交流学习。; 适合人群:所有对C#编程感兴趣的开发者,无论是初学者还是有经验的专业人士。; 使用场景及目标:①初学者可以通过基础资源快速入门C#编程,掌握基本语法和面向对象编程;②进阶开发者可以利用提供的资源深入理解C#特性,如并发编程、异步编程等;③高级开发者则可以通过高级资源和实战项目提升技术水平,解决复杂问题。; 其他说明:文中提到的资源不仅限于理论学习,还包括大量实战项目和开源项目,鼓励开发者在实践中不断积累经验。同时,活跃的社区和论坛也为开发者提供了良好的交流平台,有助于解决问题和获取最新资讯。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值