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

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

LeetCode-TwoSum

2019-11-14 14:53:59
字體:
供稿:網(wǎng)友

題目:

Given an array of integers, 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

思路:兩層for循環(huán)

package sum;public class TwoSum {    public int[] twoSum(int[] nums, int target) {        int len = nums.length;        int[] res = new int[2];        for (int i = 0; i < len - 1; ++i) {            res[0] = i + 1;            int rem = target - nums[i];            for (int j = i + 1; j < len; ++j) {                if (nums[j] == rem) {                    res[1] = j + 1;                    return res;                }            }        }                return res;    }        public static void main(String[] args) {        // TODO Auto-generated method stub        TwoSum t = new TwoSum();        int[] nums = {2, 7, 11, 15};        int target = 9;        int[] res = t.twoSum(nums, target);        System.out.PRintln(res[0]);        System.out.println(res[1]);    }}

 


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 安新县| 灵宝市| 广宗县| 乡宁县| 易门县| 巨鹿县| 天柱县| 丰县| 丘北县| 方正县| 平度市| 竹北市| 城市| 鸡西市| 德化县| 新野县| 阳高县| 遵化市| 安陆市| 青浦区| 古蔺县| 五寨县| 广灵县| 额尔古纳市| 霞浦县| 安义县| 松滋市| 民丰县| 延庆县| 博白县| 田东县| 霍山县| 鹰潭市| 桃园市| 武宁县| 蕉岭县| 广德县| 永丰县| 太仓市| 彩票| 巫溪县|