leetcode algorithms: two sum
来源:互联网 发布:杭州网络 编辑:程序博客网 时间:2024/06/15 01:29
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
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
下面是我的解法(感觉leetcode没有acm oj要求那么那么高),其中注释代码为普通解法。
package com.my.own;import java.util.Hashtable;import java.util.Scanner;public class Solution { public static int[] twoSum(int[] nums, int target) { int[] temp = new int[2];// for(int i=0; i<nums.length -1; i++){// for(int j=i+1; j<nums.length; j++){// if(nums[i] + nums[j] == target){// temp[0] = i;// temp[1] = j;// break;// }// }// } Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>(); for(int i=0; i<nums.length; i++){ ht.put(nums[i] , i); } for(int i=0; i<nums.length; i++){ if(ht.containsKey(target - nums[i])){ temp[0] = i + 1; if(ht.get(target - nums[i]) != i){ temp[1] = ht.get(target - nums[i]) + 1; break; } } } return temp; } public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.printf("please input string split by space......\n"); String s = in.nextLine(); String[] temp = s.split(" "); int[] array = new int[temp.length]; for(int i=0; i<temp.length; i++){ array[i] = Integer.parseInt(temp[i]); } System.out.printf("please input target.......\n"); int target = in.nextInt(); int[] result = twoSum(array, target); System.out.printf("result is:index1=%d, index2=%d\n", result[0], result[1]); }}
0 0
- leetcode algorithms: two sum
- Leetcode-Algorithms Two Sum
- LeetCode Algorithms 1. Two Sum
- leetcode Algorithms 1. Two Sum
- LeetCode Algorithms #1 Two Sum
- [LeetCode-Algorithms-1] "Two Sum" (2017.9.8)
- 算法设计Week1 LeetCode Algorithms Problem #1 Two Sum
- Algorithms(一)Two Sum
- 【Leetcode】Two Sum (Sum)
- Leetcode-Algorithms Add Two Numbers
- LeetCode-algorithms 39. Combination Sum
- LeetCode-algorithms 15. 3Sum
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- 谈如何将android studio项目转换成eclipse
- Doom3-BFG引擎-Review 1 (初始介绍)
- asa 5512 端口映射问题
- EIP寄存器
- 2015年个人规划-成为一名合格程序员
- leetcode algorithms: two sum
- android.os.NetworkOnMainThreadException异常
- [Python]断言assert的用法
- 在struts2的配置文件中用图形化的界面快速include其他struts.xml
- GeoServer:代码实现批量发布地图服务
- 北林校赛 北林oj 1332 冰尘君与扑克魔术
- Linux下激活超级用户root
- 十一周——继承与派生——项目一 教师兼干部类
- 前台照片展示的js实现