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 and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2   返回的是下标加1

这里已经是有序的数组,所以不需要像无序一样使用hashmap了。这里直接可以从两端向中间移。见代码

class Solution {
public int[] twoSum(int[] numbers, int target) {
if(numbers==null||numbers.length==0) return null;
int[] re=new int[2];
//从前后一起向中间遍历,因为有序,可以这样做
for(int i=0,j=numbers.length-1;i<j;){
if(numbers[i]+numbers[j]==target){
re[0]=i+1;
re[1]=j+1;
return re;
}else if(numbers[i]+numbers[j]>target){
j--; //因为有序,当两者相加大于target,说明需要减小,右边的左移
}else{
i++;
}
} return re;
} }

当然,因为有序,也可以使用二分查找。从头开始遍历每个元素,在该元素右边的数组中二分查找target-该元素,没有就遍历下一个元素。二分查找不用管该元素的左边元素,因为是从左边开始遍历的,在右边找不到对应的,所以遍历到右边时,左边肯定是没有对应元素的。

见代码,这是c++代码,原理是一样的,看关键步骤。。这个运行时间大于上面的代码,这里主要掌握思路,也是一种解法

vector<int> twoSum(vector<int> &numbers, int target) {
if(numbers.empty()) return {};
for(int i=0; i<numbers.size()-1; i++) {//遍历所有元素
int start=i+1, end=numbers.size()-1, gap=target-numbers[i];
while(start <= end) { //在右边的元素中使用二分查找与该元素对应的元素。
int m = start+(end-start)/2;
if(numbers[m] == gap) return {i+1,m+1};
else if(numbers[m] > gap) end=m-1;
else start=m+1;
}
}
}

two sum II的更多相关文章

  1. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  2. Path Sum II

    Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...

  3. [leetcode]Path Sum II

    Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...

  4. 【leetcode】Path Sum II

    Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...

  5. 32. Path Sum && Path Sum II

    Path Sum OJ: https://oj.leetcode.com/problems/path-sum/ Given a binary tree and a sum, determine if ...

  6. LeetCode: Path Sum II 解题报告

    Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals ...

  7. 【leetcode】Combination Sum II

    Combination Sum II Given a collection of candidate numbers (C) and a target number (T), find all uni ...

  8. [LeetCode] #167# Two Sum II : 数组/二分查找/双指针

    一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...

  9. leetcode2 Two Sum II – Input array is sorted

    Two Sum II – Input array is sorted whowhoha@outlook.com Question: Similar to Question [1. Two Sum], ...

  10. hdoj 1977 Consecutive sum II

    Consecutive sum II Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Other ...

随机推荐

  1. 简单RPC实现之Netty实现

    所谓RPC就是远程方法调用(Remote  Process Call ),简单的来说就是通过MQ,TCP,HTTP或者自己写的网络协议来传输我要调用对方的什么接口,对方处理之后再把结果返回给我.就这么 ...

  2. Sql Server服务远程过程调用失败

    由于开发系统,需要vs版本统一,于是经过了昨天一整天艰苦卓绝的斗争,小编终于成功的写在了13版本的vs,重新装上了12版本的vs,本来想着,12版本的vs搭建成功了,就赶快搭建框架,然后敲例子,可是天 ...

  3. (NO.00004)iOS实现打砖块游戏(十二):伸缩自如,我是如意金箍棒(上)!

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请告诉我,如果觉得不错请多多支持点赞.谢谢! hopy ;) 通用的星星类已经完成了,下面我们来实现具体的变长和缩短道具. 变 ...

  4. 【一天一道LeetCode】#191. Number of 1 Bits

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Write a ...

  5. 基于androidpn客户端修改的AndroidPNClient

    最近在做推送,采用的框架是androidpn,但对于客户端实在是修改得受不了了,特别是重连和连接那一块,有些BUG的修改实在是难以下手,比如在重连那里,原来的写法是在死循环中不断调用 xmppMana ...

  6. StringBuffer与StringBuilder详解

    刚刚在参加网易实习生在线考试的时候,出了一道选择题谈到了StringBuilder这个类的一些选项,虽然那道题自己做对了,但是也提醒了我应该好好了解一些StringBuffer与StringBuild ...

  7. android官方技术文档翻译——Android Lint

    本文译自androd官方技术文档<Android Lint>,原文地址:http://tools.android.com/tips/lint. 本文地址:http://blog.csdn. ...

  8. (NO.00001)iOS游戏SpeedBoy Lite成形记(十三)

    游戏特效部分就先这样了,因为毕竟是Lite版本,而且是第一个App,所以咱们把主要精力放在游戏可玩逻辑上吧(虽然已经厚颜无耻的加了不少特效了). 说句题外话:游戏美工是独立开发者不可逾越的鸿沟,是无法 ...

  9. NDK开发环境安装,CDT安装,Cygwin安装

     1.为eclipse增加c和c++的开发插件 Help中的install new software 选择 Helios-http://download.eclipse.org/release/h ...

  10. (C++)string类杂记

    本文特记录C++中string类(注意string是一个类)的一些值得注意的地方. string类的实例是以‘\0'结束的吗? 这个问题有时还真容易混淆,因为我们可能会将 C++ 语言中的string ...