国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 辽宁省| 望谟县| 贵定县| 绥棱县| 麦盖提县| 江陵县| 通海县| 灯塔市| 南投市| 内乡县| 集安市| 图木舒克市| 来凤县| 阳城县| 武宁县| 攀枝花市| 巩义市| 江口县| 白玉县| 福安市| 金川县| 宜川县| 莎车县| 吴忠市| 札达县| 绥阳县| 梅河口市| 都昌县| 麟游县| 肇庆市| 敦煌市| 新郑市| 贡觉县| 泉州市| 德州市| 句容市| 塔城市| 都昌县| 萍乡市| 忻州市| 九江县|