1. Two Sum
来源:互联网 发布:域名必须实名认证吗 编辑:程序博客网 时间:2024/06/10 20:14
1. Two Sum
My SubmissionsTotal Accepted: 210007 Total Submissions: 937405 Difficulty: Easy
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
74ms:
public class Solution { public int[] twoSum(int[] nums, int target) { int [] result=new int[2]; if(nums.length==2){ result[0]=0; result[1]=1; } if(nums.length>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){ result[0]=i; result[1]=j; } } } } return result; }}
5ms:
public class Solution { public int[] twoSum(int[] nums, int target) { int[] nums_sorted=new int[nums.length]; System.arraycopy(nums,0,nums_sorted,0,nums.length); //Quicksort. Arrays.sort(nums_sorted); //Find the two numbers. O(n) int start=0; int end=nums_sorted.length; while(start<end){ while(nums_sorted[start]+nums_sorted[--end]>target); if(nums_sorted[end]+nums_sorted[start]==target) break; while(nums_sorted[++start]+nums_sorted[end]<target); if(nums_sorted[end]+nums_sorted[start]==target) break; } //find the indices of the two numbers int[] ret=new int[2]; int index=0; int a=nums_sorted[start]; int b=nums_sorted[end]; for(int i=0;i<nums.length;i++) if(nums[i]==a || nums[i]==b) ret[index++]=i; return ret; }}
8ms:利用hash表
public class Solution {public static void main(String[] args) {int[] a = { 2, 7, 11, 15 };System.out.println(twoSum(a, 9));}public static int[] twoSum(int[] nums, int target) { int[] result = new int[2]; int n2; Integer idx; Map<Integer, Integer> map = new HashMap<Integer, Integer>(nums.length); for (int i = 0; i < nums.length; i++) {map.put(nums[i], i);} for (int i = 0; i < nums.length - 1; i++) {n2 = target - nums[i];idx = map.get(n2);if(idx != null && idx > i){result[0] = i;result[1] = idx;break;}} return result; }}
1 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- Ubuntu12.10将应用程序添加到启动器(转载)
- JqPagination动态分页,每次点击下一页都加载一次后台
- C++实验2-学生成绩
- Android用Websocket实现聊天室
- Ubuntu 下mininet使用源码安装
- 1. Two Sum
- ubuntu 12.04下开启root图形界面登录
- 自定义控件之绘图篇(一):概述及基本几何图形绘制
- 算法之大整数乘法
- 类像“一台数据引擎”
- Apache 403 Forbidden:You don't have permission to access / on this server.
- hadoop入门教程-hadoop是什么
- java中单项链表实现方法:增加、删除、插入数据
- Ubuntu 12.4 配置android开发环境(转载)