国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 秭归县| 临夏市| 星座| 烟台市| 进贤县| 鹰潭市| 昌图县| 西宁市| 成都市| 南乐县| 奉化市| 天镇县| 拉孜县| 墨竹工卡县| 龙岩市| 巴彦淖尔市| 原平市| 三亚市| 新巴尔虎右旗| 缙云县| 南汇区| 济阳县| 新津县| 新乡市| 义马市| 青龙| 开封县| 贺兰县| 武威市| 崇左市| 临洮县| 鄄城县| 普陀区| 甘孜县| 河北省| 大足县| 郁南县| 陆川县| 伊宁县| 墨脱县| 历史|