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
public class Solution { public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; int i, j; for (i = 0; i < nums.length; i++) { for (j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { result[0] = i+1; result[1] = j+1; } } } return result; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/64478.html
摘要:解題思路利用遞歸,對(duì)于每個(gè)根節(jié)點(diǎn),只要左子樹和右子樹中有一個(gè)滿足,就返回每次訪問一個(gè)節(jié)點(diǎn),就將該節(jié)點(diǎn)的作為新的進(jìn)行下一層的判斷。代碼解題思路本題的不同點(diǎn)是可以不從開始,不到結(jié)束。代碼當(dāng)前節(jié)點(diǎn)開始當(dāng)前節(jié)點(diǎn)左節(jié)點(diǎn)開始當(dāng)前節(jié)點(diǎn)右節(jié)點(diǎn)開始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...
摘要:只要我們能夠有一個(gè)以某一中間路徑和為的哈希表,就可以隨時(shí)判斷某一節(jié)點(diǎn)能否和之前路徑相加成為目標(biāo)值。 最新更新請(qǐng)見:https://yanjia.me/zh/2019/01/... Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addin...
摘要:動(dòng)態(tài)規(guī)劃法用表示最大子數(shù)組的結(jié)束下標(biāo)為的情形,則對(duì)于,有這樣就有了一個(gè)子結(jié)構(gòu),對(duì)于初始情形,遍歷就能得到這個(gè)數(shù)組,其最大者即可最大子數(shù)組的和。動(dòng)態(tài)規(guī)劃法想法巧妙,運(yùn)行效率也高,但是沒有普遍的適用性。 問題簡介 ??本文將介紹計(jì)算機(jī)算法中的經(jīng)典問題——最大子數(shù)組問題(maximum subarray problem)。所謂的最大子數(shù)組問題,指的是:給定一個(gè)數(shù)組A,尋找A的和最大的非空連續(xù)...
摘要:為了避免得到重復(fù)結(jié)果,我們不僅要跳過重復(fù)元素,而且要保證找的范圍要是在我們最先選定的那個(gè)數(shù)之后的。而計(jì)算則同樣是先選一個(gè)數(shù),然后再剩下的數(shù)中計(jì)算。 2Sum 在分析多數(shù)和之前,請(qǐng)先看Two Sum的詳解 3Sum 請(qǐng)參閱:https://yanjia.me/zh/2019/01/... 雙指針法 復(fù)雜度 時(shí)間 O(N^2) 空間 O(1) 思路 3Sum其實(shí)可以轉(zhuǎn)化成一個(gè)2Sum的題,...
摘要: 112. Path Sum Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node...
閱讀 2617·2023-04-25 22:09
閱讀 2848·2021-10-14 09:47
閱讀 1956·2021-10-11 11:10
閱讀 2696·2021-10-09 09:44
閱讀 3393·2021-09-22 14:57
閱讀 2507·2019-08-30 15:56
閱讀 1627·2019-08-30 15:55
閱讀 787·2019-08-30 14:13