leetcode之two Sum
来源:互联网 发布:.top域名好优化吗 编辑:程序博客网 时间:2024/05/17 08:37
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
Output: index1=1, index2=2
源代码如下:
publicpublic static int[] twoSum(int[] numbers, int target) { if(numbers.length <= 1) return null; int[] result = new int[2]; Arrays.sort(numbers); int n = numbers.length; for(int i = 0, j = n - 1; i <= j;) { if(numbers[i] == target - numbers[j]) { if(i < j){ result[0] = i + 1; result[1] = j + 1; }else{ result[0] = j + 1; result[1] = i + 1; } break; }else if(numbers[i] < target - numbers[j]){ System.out.println("ok12"); ++ i; }else{ System.out.println("ok13"); j --; } } return result; }/* 如果不需要两个数的下标值,则可以先对数组排序,然后用两个指针i,j从数组的头尾同时遍历数组,如果num[i] + num[j] > target,则j --;如num[i] + num[j] < target, 则i ++;直到num[i] + num[j] == target.(注:该思路来源于《程序员编程艺术》) 代码如下: */ public static int[] twoSum(int[] numbers, int target) { if(numbers.length <= 1) return null; int[] result = new int[2]; Arrays.sort(numbers); int n = numbers.length; for(int i = 0, j = n - 1; i <= j;) { if(numbers[i] == target - numbers[j]) { if(i < j){ result[0] = i + 1; result[1] = j + 1; }else{ result[0] = j + 1; result[1] = i + 1; } break; }else if(numbers[i] < target - numbers[j]){ System.out.println("ok12"); ++ i; }else{ System.out.println("ok13"); j --; } } return result; }0 0
- 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
- 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
- 深入理解debuginfo
- C语言中声明及定义的区别:【C专家编程】
- UVA 11987 第一次并查集
- Android四大基本组件
- poj1004——Financial Management
- leetcode之two Sum
- iOS多线程编程(一)NSThread
- 程序猿每天面对电脑,如何对付眼睛干涩
- ACM-BFS之非常可乐——hdu1495
- IOS . OC多参数函数
- 线程之间的共享内容
- c++ 大数类 大数模板
- 中国需要更多地研发先进海上装备
- UVa11549 - Calculator Conundrum (Floyd判圈法)