题目:
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]
关注
打赏
- 【Leetcode】剑指Offer 34:二叉树中和为某一值的路径
- 【Leetcode】剑指Offer 33:二叉搜索树的后序遍历序列
- 【Leetcode】剑指Offer 32-III: 从上到下打印二叉树 III
- 【Leetcode】剑指Offer 32-II: 从上到下打印二叉树 II
- 【Leetcode】剑指Offer 32-I:从上到下打印二叉树
- 【Leetcode】剑指Offer 31:栈的压入、弹出序列
- 【Leetcode】剑指Offer 30:包含min函数的栈
- 【Leetcode】剑指Offer 29:顺时针打印矩阵
- 【Leetcode】剑指Offer 28:对称的二叉树
- 【Leetcode】剑指Offer 27:二叉树的镜像