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

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

LeetCode 1. Two Sum

2019-11-08 02:11:55
字體:
供稿:網(wǎng)友

問題描述

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

給定一個(gè)整形數(shù)組,返回兩個(gè)數(shù)的索引,使對(duì)應(yīng)的數(shù)組元素之和為目標(biāo)值。 每次輸入都恰好有且只有一組解,單個(gè)數(shù)組元素只能使用一次。

輸入輸出

Example: Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

解法

public class Solution { public int[] twoSum(int[] nums, int target) { int[] rst = new int[2]; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { rst[0] = i; rst[1] = j; break; } } } return rst; }}

遍歷數(shù)組求和,此法需遍歷2次,使用HashMap好像只需要遍歷一次,日后補(bǔ)上。

測(cè)試

public static void main(String[] args) { int[] i = {2, 7, 11, 15}; int[] rst = new int[2]; Solution sl =new Solution(); rst = sl.twoSum(i, 22); System.out.PRintln(rst[0]); System.out.println(rst[1]); }
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 定襄县| 乌海市| 屯留县| 额济纳旗| 海阳市| 吉木萨尔县| 赤城县| 井研县| 五寨县| 胶州市| 宝兴县| 开阳县| 兴隆县| 昂仁县| 祥云县| 砀山县| 黄山市| 锡林浩特市| 阜平县| 修文县| 绥化市| 安多县| 泰州市| 无棣县| 平江县| 大城县| 芦溪县| 周口市| 中西区| 米林县| 聂荣县| 岐山县| 莒南县| 沈丘县| 阿拉善右旗| 嵊泗县| 依兰县| 中宁县| 惠州市| 皮山县| 吴忠市|