`
liubangchuan
  • 浏览: 16101 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

LeetCode Problem:在一个数组中求满足和等于一定条件的两个数

 
阅读更多

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

 

这个题目编程之美上面也提到了,不过这里的要求是要返回值在序列中的索引

 解法一:

借助于哈希表,时间复杂度为O(n),空间复杂度最坏情况下O(n),代码是java语言

	public static int[] twoSumByHash(int[] numbers, int target){
		if(numbers == null || numbers.length < 2){
			return new int[]{-1,-1};
		}
		Map<Integer,Integer> map = new HashMap<Integer,Integer>();
		map.put(target - numbers[0], 0);
		for(int i=1;i<numbers.length;i++){
			if(map.keySet().contains(numbers[i])){
				return new int[]{map.get(numbers[i])+1,i+1};
			}else{
				map.put(target - numbers[i], i);
			}
		}
		return new int[]{-1,-1};
	}

 解法二:

先排序,然后从两头遍历,时间复杂度为O(n)

public static int[] twoSum(int[] numbers, int target) {
		int[] nums = numbers.clone();
		Arrays.sort(numbers);
		int i = 0;
		int j = numbers.length - 1;
		while(i<j){
			if(numbers[i] + numbers[j] == target){
				break;
			}else if (numbers[i] + numbers[j] < target){
				i++;
			}else{
				j--;
			}
		}
		if(i< j ){
			int[] result = new int[2];
			int count = 0;
			for(int k=0;k<nums.length;k++){
				if(nums[k] == numbers[i] || nums[k] == numbers[j]){
					result[count++]=k+1;
				}
			}
			return result;
		}

		return new int[]{-1,-1};
	}

 

 

分享到:
评论

相关推荐

    算法-leetcode-剑指offer上的题很多

    - **两数之和(2 Sum)**: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。 - **数组的K个数之和(Subarray Sum K)**: 给定一个整数数组和一个整数 k,...

    LeetCode_java_leetcode_刷题_

    4. **排序与查找**:快速排序、归并排序、二分查找等经典算法经常出现在LeetCode题目中,比如"Median of Two Sorted Arrays"要求找到两个有序数组的中位数,这需要灵活运用二分查找。 5. **递归与迭代**:如"Binary...

    leetcode_problem_rating:每周两次leetcode中自我计算的问题评分

    在IT行业中,LeetCode是一个非常受欢迎的在线平台,它提供了大量的编程题目,旨在帮助程序员提升算法和数据结构技能。这个“leetcode_problem_rating”项目显然与LeetCode相关,特别是关于问题难度的自我评估。这里...

    判断青蛙过河leetcode-leetcode:https://leetcode-cn.com/problemset/all/

    判断青蛙过河leetcode 目录 leetcode 打印不重复元素 √ 4、二维数组中查找目标值(从...一个整数分解成两个质数和 √ 数据分类(int转16进制) √ 设计模式 util doc 基础扎实全面:编程语言、数据结构、算法等 高质量代

    leetcode答案-algorithm_problem_solving:CTCI书籍和Leetcode问题的解决方案

    答案CTCI书籍和Leetcode问题的解决方案 类别 名称 问题 回答 笔记 个人评分 细绳 是独特的 CTCI 1-1 + 细绳 检查排列 CTCI 1-2 + :star: 细绳 网址化 CTCI 1-3 + 细绳 Penidrom 排列 CTCI 1-4 —— :star: 细绳 一走...

    Python_leetcode.zip

    在二叉搜索树中寻找最近的两个节点,要求改变路径中的一个节点。Python的递归和树遍历策略在这里得到应用,展示了Python在数据结构操作上的灵活性。 "regular-expression-matching.py"考察的是字符串匹配和回溯算法...

    leetcode1-240题中文题解,md格式,java

    1. leetCode-126-Word-LadderII.md:这涉及到第126题,词梯问题,通常是一个字符串转换问题,目标是找到两个单词之间的最短转换序列,每次只改变一个字母。 2. leetcode-224-Basic-Calculator.md:这是第224题,基础...

    判断链表是否为回文链表leetcode-leetcode:https://leetcode.com/problemset/algorithms

    问题:最长公共前缀编写一个函数来查找字符串数组中最长的公共前缀字符串。 ###a13 问题:罗马到整数给定一个罗马数字,将其转换为整数。 输入保证在 1 到 3999 的范围内。 ###a12 问题:整数转罗马|| 给定一个整数...

    leetcode285-leetcode:leetcode

    leetcode 285 leetcode ID problem 难度 使用语言 思路 提交次数 WA点 ...两数之和 ...两数相加 ...三数之和 ...合并两个有序链表 ...两数相除(不使用乘法除法) ...用被除数不断减去除数直至被减数为负(TLE),每次将...在排序数组中查

    JavaScript_LeetCode Solutions A Record of My Problem Solving Jo

    在LeetCode的许多问题中,合理利用这些异步处理方法能有效提高代码的执行效率和可读性。 在LeetCode的JavaScript解题过程中,会遇到各种算法问题,如排序、查找、图论、动态规划等。这些问题往往需要对数据结构有...

    leetcode添加元素使和等于-leetcode:解决leetcode问题的python/JAVA代码

    1:最直接的方式直接双层遍历该数组,找到两个数相加等于该结果。时间复杂度为O(n^2 )。该方法的变种就是遍历一次数组,然后在该数组中搜索target-x是否存在。但是时间复杂度都是O(n^2 ),空间复杂度是T(n) 2:利用...

    leetcode双人赛-leetcode-1:leetcode-1

    :计算数组中每对两个元素的总和。 对于每个 twoSum i ,检查是否存在另一个 twoSum j ,其中i + j = target 。 AddBinary :简单的问题。 AddTwoNumbers :简单的问题。 Anagrams :简单的#hashtable问题。 ...

    leetcode题库-leetcode:算法代码-JavaScript

    例如,"两数之和"(Two Sum)题目要求你在数组中找到两个数,使得它们的和等于给定的目标值,这通常涉及到哈希表的使用。 2. 算法:LeetCode的算法题目涵盖了排序(快速排序、归并排序、冒泡排序等)、搜索(二分...

    leetcode变形词-Right-Wing-Problem:涉及数组迭代、递归和OutOfBounds异常的小算法问题

    右翼问题总结如下:给定一个整数数组,其值小于或等于所述数组的长度,你如何判断从位置 0 开始的标记是否有可能到达数组的最后一个位置?大批? 标记可以向两个方向移动:向左或向右。 位移是存储在标记当前“站立...

    leetcode答案-LeetCode:LeetCode练习答案

    - `problem1_两数之和/`:包含问题1的解决方案,即找到数组中两个数使得它们的和等于一个特定的目标值。 - `problem2_两数相乘/`:找到数组中两个数的最大乘积。 - ... - `problemN_/`:其他题目对应的解决方案...

    leetCode:Leetcode解决方案

    在LeetCode中,数组是最常见的数据结构,如Two Sum(两数之和)、Merge Intervals(合并区间)等问题都涉及到数组的操作。 2. 链表:链表是一种动态数据结构,通过节点间的指针链接元素。例如,Reverse Linked List...

    leetcode不会-ProblemSolving-LeetCode:问题解决-LeetCode

    残酷:两个循环或签in def isUnique ( self , astr ): for i in range ( len ( astr )): if astr [ i ] in astr [ i + 1 :]: return False return True astr[i] in astr[i+1:]检查astr[i] in astr[i+1:]也在引擎盖下...

    Leetcode:LeetCode 刷题总结

    例如,"两数之和"(Two Sum)是经典的数组问题,要求找到数组中使得它们相加等于特定目标值的两个元素的索引。 2. **链表**:链表问题涉及节点的插入、删除、反转、合并等操作。例如,"两链表的交点"(Intersection...

    LeetCode判断字符串是否循环-ACMTraining:同步需求

    即只关心正负而不关心数值,可以将一个正数数组原地作为一个布尔数组使用。关心的信息的维度不同,可以让一个数组包含多个维度的信息。 Problem42 of LeetCode 题目:给定 n 个非负整数表示每个宽度为 1 的柱子的...

    LeetCode:LeetCode刷题

    例如,"两数之和"(Two Sum)问题,要求找到数组中和为目标值的两个数的索引。 2. **链表(Linked List)**:链表操作包括插入、删除、反转、合并等。例如,"两数相加"(Add Two Numbers)问题,需要将两个链表表示...

Global site tag (gtag.js) - Google Analytics