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
- twoSum问题 两个数组相加为确定值,输出对应数组的位置
- LeetCode 1. Two Sum--数组中两元素相加为该数值,输出对应的两个索引
- Two Sum 从数组中找到两个位置的值相加和为给定目标的值
- 找出数组中和为给定的值的两个数(twoSum)
- 两个数组逆排元素对应相加,返回一个数组
- 输入一个无序的数组,按照一定的方式输出结果, 要求两个数的相加和为10
- 两个数组元素(相加、相乘)相关的问题
- 两个有序数组相加和的topK问题
- 167 Two Sum II (给定数组求相加为定值的两个数)
- 用运算符重载“+”的方法直接实现两个一维数组对应元素的相加
- 两个数组相加
- 输出递增数组中和为sum的两个数
- 两个一维数组合并为对应的二维数组(array_merge_recursive)
- 找到一个数组中相加为特定数值的两个元素
- 输出数组中所有三个数相加为0的解
- 输出数组中所有三个数相加为0的解
- 【C语言】数组对应位置交换值
- 两个四维数组相加
- SeaSar2之系统拦截器-yellowcong
- java实现定时任务的三种方法
- HTML 多行文本省略显示代码
- 编程语言中,取余和取模的区别到底是什么?
- 接口性能测试实战小结(附点评)
- twoSum问题 两个数组相加为确定值,输出对应数组的位置
- 执行Iterator.remove()方法时出现Java.lang.IllegalStateException异常
- Android学习笔记二十一之AutoCompleteTextView(自动提示文本框)和MutiAutoCompleteTextView(多提示项的自动提示文本框)
- 动态页面和静态页面区别
- jquery操作select(取值,设置选中)
- 你的 bug -- Internal GD font () not available. Use only 1-5. laravel 5.5 验证码
- Java中HashMap,LinkedHashMap,TreeMap的区别
- ubuntu安装apktool
- 在idea中使用Mybatis-generator插件快速生成代码