常考数据结构与算法:两数之和
生活随笔
收集整理的這篇文章主要介紹了
常考数据结构与算法:两数之和
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
給出一個整數數組,請在數組中找出兩個加起來等于目標值的數,
你給出的函數twoSum 需要返回這兩個數字的下標(index1,index2),需要滿足?index1 小于index2.。注意:下標是從1開始的
假設給出的數組中只存在唯一解
例如:
給出的數組為 {20, 70, 110, 150},目標值為90
輸出 index1=1, index2=2
?
?
public class TwoSum {public static void main(String[] args) {int[] arr = {20, 70, 110, 150};TwoSum ts = new TwoSum();int[] a =ts.twoSum(arr,90);for(int t : a){System.out.println(t);}}/**** @param numbers int整型一維數組* @param target int整型* @return int整型一維數組*/public int[] twoSum (int[] numbers, int target) {int[] arr = new int[2];if(numbers == null || numbers.length == 1){return arr;}for (int i = 0; i < numbers.length-1; i++) {for (int j = i+1; j < numbers.length; j++) {if(numbers[i] + numbers[j] == target){arr[0] = i+1;arr[1] = j+1;}}}return arr;} }?
總結
以上是生活随笔為你收集整理的常考数据结构与算法:两数之和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 计算机网络:TCP
- 下一篇: 常考数据结构与算法:将字符串转为整数