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%的人。

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

LeetCode第一题

LeetCode(1)--TwoSum

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

【7月3日】LeetCode刷题日志(一):TwoSum

【七月三日】LeetCode刷题日志(一):TwoSum好久没有更新了。现在开始刷题package com.njust.day0703;import java.util.ArrayList;/** ...

LeetCode-TwoSum

LeetCode-1.TwoSumQuestionGiven an array of integers, return indices of the two numbers such that the...

leetcode TwoSum

-Given an array of integers, find two numbers such that they add up to a specific target number.The ...

LeetCode TwoSum 找到两个数字之和

这题是说存在一个整数数组,要求找到两个数字相加之后可以和目标整数相等。题目里面存在一个问题就是这个数组是无序的,另外就是这个数组中可能存在两个相等的数字,要求我们返回这个数在数组中对应的位置,提示这个...

leetcode-1 TwoSum

Given an array of integers, find two numbers such that they add up to a specific target number. The...

LeetCode_1 TwoSum

看书虽然有必要,但是光看书大家斗志到是没用的,但是没办法,科研项目和互联网没关,只能找点题目来刷了! 不多说,开始! LeetCode_1   TwoSum 题目说明: Given an arr...

LeetCode-TwoSum

题目 Two Sum
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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