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