【leetcode系列】Two Sum
来源:互联网 发布:java俄罗斯方块代码 编辑:程序博客网 时间:2024/06/18 04:33
解法一,我自己想的,有点弱,时间复杂度O(n^2)。
public class Solution {public int[] twoSum(int[] numbers, int target) {int[] result = new int[2];for (int i = 0; i < numbers.length; i++) {for (int j = i + 1; j < numbers.length; j++) {if (numbers[i] + numbers[j] == target) {result[0] = i;result[1] = j;}}}if (result[0] == 0) {if (result[1] != 1) {int tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;} else {int tmp = numbers[1];numbers[1] = numbers[2];numbers[2] = tmp;result[1] = 2;tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;}}return result;}public void arrayPrint(int[] array) {for (int i = 0; i < array.length; i++) {System.out.print(array[i] + " ");}System.out.println();}public static void main(String[] args) {int[] numbers = { 11, -22, 12, 7, 2 };int target = 9;Solution mSolution = new Solution();mSolution.arrayPrint(numbers);int[] result = mSolution.twoSum(numbers, target);mSolution.arrayPrint(result);mSolution.arrayPrint(numbers);}}
解法二,网上大牛的,点击打开链接,很巧妙,用java的hashtable,典型的空间换时间,时间复杂度O(n),但是要满足下标的要求,必须在找出满足条件的数字后再重新排个序,下面是我稍微修改的代码:
public int[] twoSum_2(int[] numbers, int target) {int[] result = new int[2];HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();for(int i = 0; i < numbers.length; i++) {if(hm.get(target - numbers[i]) != null) {result[0] = hm.get(target - numbers[i]);result[1] = i;} else {hm.put(numbers[i], i);}}if (result[0] == 0) {if (result[1] != 1) {int tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;} else {int tmp = numbers[1];numbers[1] = numbers[2];numbers[2] = tmp;result[1] = 2;tmp = numbers[0];numbers[0] = numbers[1];numbers[1] = tmp;result[0] = 1;}}return result;}
0 0
- 【leetcode系列】Two Sum
- 【LeetCode】two sum系列
- leetcode解题系列:Two Sum
- LeetCode系列之Two sum
- [leetcode刷题系列]Two Sum
- leetcode系列(29)Two Sum
- leetcode【1+167 Two Sum 系列】【python】
- 《Leetcode系列》C++实现:1-two sum
- LeetCode题解系列--1. Two Sum
- 【Leetcode】Two Sum (Sum)
- 【leetcode X Sum 系列】Two Sum|3Sum|3Sum Closest|4Sum
- LeetCode OJ 系列之1 Two Sum --Python
- 算法练习专题——LeetCode系列之 Two Sum
- 算法系列--Two Sum
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- NSObject扩展
- 发布webservice接口时报错-HTTP Status 500 - File "/axis2-web/listSingleService.jsp" not found
- HashMap和TreeMap区别
- 关于CCCallFunc、CCCallFuncN和CCCallFuncND的使用
- ifconfig 配置网卡
- 【leetcode系列】Two Sum
- NSFileManager扩展
- Updater-script升级脚本阅读指南
- 浅谈数据库中的触发器
- 保护企业网络的SSL VPN协议
- 【Android】禁止锁屏,保持高亮
- HDU1708 Fibonacci String 动态规划
- 苹果原生地图API封装
- 关于cocos2dx客户端程序的自动更新解决方案