LeetCode - TwoSumII - Frequent

来源:互联网 发布:笔记本如何安装软件 编辑:程序博客网 时间:2024/06/14 18:06

Two Sum II, 是leetcode付费的部分,在这里贴下题目吧,这样不想付费的也可以看看,非常简单,比two sum还简单:

https://leetcode.com/problems/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. 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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2


代码就是两边逼近,因为这里不需要排序,所以也不用hashmap来记录index,直接两边逼近就行了

    public int[] twoSum(int[] numbers, int target) {        int[] rst = new int[2];        int start = 0;        int end = numbers.length-1;        while(start<end){            if((numbers[start]+numbers[end])==target){                rst[0]=start+1;                rst[1]=end+1;                return rst;            }            else if((numbers[start]+numbers[end])<target) start++;            else if((numbers[start]+numbers[end])>target) end--;        }        return rst;    }

空间复杂度O(1), 时间复杂度O(n)

看了一下leetcode给的tag,这还可以用binary search的解法,不过我目前觉得需要O(n*lgn)的时间,所以这里不写binary search的解法了

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 事业单位每年福利体检有乙肝怎么办 高考失利后我该怎么办 初三了科学总是考不好怎么办 初三学生三模考的不好怎么办 高考体检检查出乙肝怎么办 高考体检单丢了怎么办 小腿弯曲没发育好怎么办? 辅警考试体能测试不合格怎么办 跑步跑不动怎么办腿软 人胖跑步跑不动怎么办 不工作每天很累怎么办 电大本科文凭毕业证掉了怎么办 要求全日制本科自考本科怎么办 毕业证被学校扣了怎么办 自考本科档案没有密封怎么办 艺术生统考没过怎么办 本科科目没考过怎么办 军校体检条丢了怎么办 学美术考了大专怎么办 音基试唱音不准怎么办 音基证书丢了怎么办 职称计算机证书丢了怎么办 30岁了 开始怀旧怎么办 31岁了 缺乏运动怎么办 30多了还一事无成未来怎么办 导师说名额已满怎么办 在中国想当大官怎么办 站久了小腿变粗怎么办 苹果x锁屏延迟怎么办 被扇了巴掌耳痛怎么办 被扇了巴掌耳鸣怎么办 水兵舞不会扭胯怎么办 我的字写得很丑怎么办 二年级学生不会造句怎么办 w10下载种子文件失败怎么办 宝宝挂水手肿了怎么办 lol有英雄皮肤没英雄怎么办 qq聊天图标粉色钥匙怎么办 和舍友相处不来怎么办 被舍友偷了东西怎么办 体育生没过线怎么办