- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
想做个算法,在leetcode上发现了这个问题
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^2)。我想知道是否有更好的方法来做到这一点?像 O(n) 或 O(nlogn)
import java.util.Arrays;
public class ReturnIndex {
public int[] twoSum(int[] numbers, int target) {
int tail = numbers.length-1;
int[] n = new int[2];
for (int i=0;i<tail;i++) {
for(int j=i+1;j<tail;j++) {
if(target ==(numbers[i]+numbers[j])) {
n[0] = i+1;
n[1] = j+1;
}
}
}
return n;
}
public static void main(String[] args) {
int[] s = {150,24,79,50,88,345,3};
int value = 200;
ReturnIndex r = new ReturnIndex();
int[] a = r.twoSum(s,value);
System.out.println(Arrays.toString(a));
}
}
最佳答案
对数组进行排序。使两个指针分别指向第一个和最后一个(x 和 X)。循环运行:
if (a[X]+a[x] > N) then X--
else if (a[X]+a[x] < N) then x++
else if (a[X]+a[x] == N) then found.
if (x > X) then no numbers exist.
O(nlogn)
时间,O(1)
内存
关于java - twoSum 算法 : How to improve this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13042798/
我有这样的问题 Given an array nums of n integers, are there elements a, b in nums such that a + b = 10? Fin
当我运行以下代码时,我得到了预期的答案 [3, 4],这是加起来成为我的目标变量的 2 个数字的索引。但是,当我将 myArray 输入更改为 []int{1,2,3,4,6,11,4,12}(我删除
#include #include #include int bins(int* p,int lo,int hi,int t) {//BinarySearch int mid=0; i
我为两个求和问题设计了三种解法 Given all arrays of integers, return indices of the two numbers such that they add u
我正在尝试使用 map 来制作此答案的算法 https://leetcode.com/problems/two-sum/#/description O(n),但出于某种原因,我在尝试的许多测试用例中得
想做个算法,在leetcode上发现了这个问题 Given an array of integers, find two numbers such that they add up to a spec
我对python绝对是菜鸟,刚开始练习leetcode。不管怎样,看看这个 TwoSum 练习:给定一个整数数组,找到两个数字,使它们加起来等于特定的目标数字。 这是我为这个练习编写的代码: clas
Leetcode Question 我已经分析了 Leetcode 问题的答案,并询问我的推理是否正确。我尝试分析何时 num = 2 和何时 num = 7。分析由//分隔。 function tw
我正在练习编码问题,但我不确定为什么我的代码不起作用(我知道它写得不是很有效:/) 给定一个数组和一个目标数字,返回数组中两个数字相加等于目标数字的索引。示例:nums = [2, 7, 11, 15
我尽量解决leetcode中的一个twoSum问题 Given an array of integers, return indices of the two numbers such that th
Given an array of integers, return indices of the two numbers such that they add up to a specific ta
我正在尝试解决 testdome.com 中的 C# 编程问题,但我发现了有关性能的问题。如何解决? 二叉搜索树 using System; public class Node { publi
我在python3中找到了如下代码: def twoSum(self, nums: List[int], target: int) -> List[int]: return sum(nums)
我是一名优秀的程序员,十分优秀!