twoSum问题 两个数组相加为确定值,输出对应数组的位置

来源:互联网 发布:php参考文献近两年 编辑:程序博客网 时间:2024/06/05 09:46

LeetCode上一个比较简单的问题

题目介绍
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。
简单来说,给定一个数组和一个确定数,有数组中的的任意两个数相加和等于给定的一个确定数,返回数组中这两个数的下标。

题目介绍给出的案例如下:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

用Java语言完成编程,首先确定解答思路。。。可以循环数组值使之相加观察是否等于确定数,并且返回输出。。。。这就很容易写出与之相关的方法,如下:

class Solution {     public int[] twoSum(int[] nums, int target) {            int[] indices = 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 ) {                        indices[0] = i;                        indices[1] = j;                    }                }            }            System.out.println(indices[0]);             System.out.println(indices[1]);             return indices;        }

只要在main函数中调用此方法即可,下面给出我自己举的数组以及程序运行答案:

class Solution {     public int[] twoSum(int[] nums, int target) {            int[] indices = 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 ) {                        indices[0] = i;                        indices[1] = j;                    }                }            }            System.out.println(indices[0]);             System.out.println(indices[1]);             return indices;        }     public static void main(String[] args) {         Solution s =new Solution();         int[] array = {1,2,3,4,5};         int target=5;     s.twoSum(array,target);             }         }

运行结果如下:
这里写图片描述
恰巧数组中第1,2位置数值相加 等于给定确定数5,结果准确

阅读全文
0 0