【leetcode】Two Sum
来源:互联网 发布:凤凰金融 以大数据 编辑:程序博客网 时间:2024/06/06 01:13
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 haveexactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].Sulution:
对于这个问题,本质上是对数组进行来遍历,通过两层循环找到,数组中的两个元素的和为target,但是要注意的是,如果没有找到两个数的和为target,则需要抛出异常,这样才是一个完整的算法!
public class Solution { public int[] twoSum(int[] nums, int target) { int i,j; int []arr = new int[2]; for(i = 0; i < nums.length-1; ++i){ for(j = i+1; j < nums.length; ++j){ if((nums[i] + nums[j]) == target) { arr[0] = i; arr[1] = j; return arr; } } } throw new IllegalArgumentException("No two sum solution"); }
Conclusion:
AC:39ms
1 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- 链栈
- 数据结构-链表
- 使用scanf的注意事项
- 第三章 函数
- Tomcat关闭过程
- 【leetcode】Two Sum
- 3 创建一个窗口
- 浅谈管理系统操作日志设计(附操作日志类)
- python中的模块查询、安装、卸载
- 14.布局
- C++构造函数初始化列表
- org.hibernate.MappingException: entity class not found
- VS 2013控制台应用程序DLL生成与调用
- 欢迎使用CSDN-markdown编辑器