leetcode算法之TwoSum

原创 2015年07月09日 19:24:46

</pre><strong>Two Sum</strong><p>Given an array of integers, find two numbers such that they add up to a specific target number.</p><p>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.</p><p>You may assume that each input would have exactly one solution.</p><p style="font-family:monospace"><strong>Input:</strong> numbers={2, 7, 11, 15}, target=9<strong>Output:</strong> index1=1, index2=2</p><p style="font-family:monospace"></p><p style="font-family:monospace"><pre name="code" class="java"> public int[] twoSum(int[] nums, int target) {
        	int arr[]=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)
				{
					arr[0]=i+1;
					arr[1]=j+1;
					return arr;
				}
			}
		}
		return null;
    }


时间复杂度:o(n*n)



 public int[] twoSum(int[] numbers, int target) {
		// TODO Auto-generated method stub
		int index1 = 0, index2 = 0, n = numbers.length;
		
		HashMap<Integer, Integer> hashmap=new HashMap<Integer, Integer>();
		for(int i=0;i<n;i++)
		{
			hashmap.put(numbers[i], i);
		}
		
		for (int i = 0; i < n; i++) {
			int m = target - numbers[i];
			Integer j=hashmap.get(m);
			boolean b =(hashmap.containsKey(m))&&(j.intValue()!=i);
			if (b) {
				//
				index1=i+1;
				index2=j+1;
				break;
			}
		}
		int[] a={index1,index2};
		return a;
	}
时间复杂度:o(n)



版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode 算法实现:TwoSum

通过了LeetCode检测,提示用了16个测试,用时492ms,超过了75%的人。
  • worsun
  • worsun
  • 2015年09月19日 12:04
  • 247

【LeetCode001算法/编程练习C++】--twoSum //从816ms到16ms的优化过程

LeetCode第一题
  • zmdsjtu
  • zmdsjtu
  • 2016年12月19日 10:21
  • 341

LeetCode/TwoSum Java

题目:Given an array of integers, return indices of the two numbers such that they add up to a specific...

LeetCode_1_TwoSum_java

Two Sum Given an array of integers, return indices of the two numbers such that they add up to a sp...
  • ac_li
  • ac_li
  • 2016年08月16日 22:08
  • 102

leetcode1 || TwoSum

Java中的Hashtable的用法:Java包含两个类,java.util.Hashtable 和java.util.HashMap,Hashtable和HashMap对象把一个key 和一个val...

Leetcode 之 twoSum, ThreeSum, FourSum(K-Sum)问题

Leetcode之k sum 问题

Leetcode001_TwoSum_Java+Python3+C++解法_补充:HashMap&Vector

题目描述 github链接 给定一个整数数组和一个特定的整数,返回和为该特定整数的两个数组元素的索引(假设发挥结果恰好唯一) 样例:给定 nums=[2,7,11,15] target=...

LeetCode题解——1TwoSum

题目: Given an array of integers, find two numbers such that they add up to a specific target n...

leetcode 1 TwoSum

leetcode 1. TwoSum问题描述: Given an array of integers, return indices of the two numbers such that th...

leetcode:TwoSum

Leetcode 对于TwoSun题目的分析,以及用hashmap巧妙求解,代码为java实现
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode算法之TwoSum
举报原因:
原因补充:

(最多只允许输入30个字)