国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

leetcode_167 Two Sum II - Input array is sorted

2019-11-06 06:25:13
字體:
供稿:網(wǎng)友

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

翻譯:從有序數(shù)組中找到兩個數(shù)使它們的和為target

法1:O(n)

public int[] twoSum(int[] numbers, int target) { int[] my = new int[2]; boolean flag =true; int i=0,j=numbers.length-1; while(flag){ while( (numbers[i]+numbers[j])>target ) j--; while( (numbers[i]+numbers[j])<target ) i++; if( (numbers[i]+numbers[j])== target ) flag =false; } my[0] =i+1; my[1] =j+1; return my; }

法2:借助 Map,時間復(fù)雜點

public int[] twoSum(int[] numbers, int target) { int[] my = new int[2]; // <數(shù)值,下標(biāo)> Map<Integer, Integer> map = new HashMap<>(); for(int i=0;i<numbers.length;i++) map.put(numbers[i], i); int i1=0,i2=0; boolean flag =true; while(flag){ if(map.containsKey(target-numbers[i1])) { i2=map.get(target-numbers[i1]); flag = false; } else i1++; } my[0] = i1+1; my[1] = i2+1; return my; }
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 德令哈市| 吴忠市| 金湖县| 衡阳市| 射洪县| 德江县| 磴口县| 许昌市| 佛教| 云南省| 舟山市| 益阳市| 报价| 拜泉县| 龙里县| 侯马市| 怀远县| 蛟河市| 花莲县| 景宁| 富平县| 邹城市| 全椒县| 镇巴县| 公主岭市| 舟曲县| 大同市| 柘荣县| 广宁县| 三原县| 南郑县| 永兴县| 东山县| 南召县| 马尔康县| 临桂县| 体育| 东海县| 苍山县| 大渡口区| 全州县|