您当前的位置: 首页 >  ar

孑渡

暂无认证

  • 4浏览

    0关注

    178博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

刷题系列(1)LeetCode167-Two Sum II - Input array is sorted

孑渡 发布时间:2020-07-21 00:02:06 ,浏览量:4

刷题系列(1)LeetCode167-Two Sum II - Input array is sorted

题目:

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. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Example: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted

说来惭愧,这学期学了算法之后第一反应竟然没有想到双指针和二分查找,实在是愚昧至极。果然脑袋很长一段时间不用是会锈住的,希望通过刷题让脑袋能正常运转起来。

  • 第一个思路

最开始的想法思路如下:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
    int flag1 = 0;
    int flag2 = 1;
    while(numbers[flag1] + numbers[flag2] != target)
    {
        if(numbers[flag1] + numbers[flag2]             
关注
打赏
1663211900
查看更多评论
0.0423s