我是靠谱客的博主 机灵夏天,这篇文章主要介绍LeetCode:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数,现在分享给大家,希望可以做个参考。

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

示例:

复制代码
1
2
3
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

思路:先在数组中找出比target小的数字记为temp然后从temp遍历数组,只要找到temp + nums[j] == target,就返回找到的这两个数的在数组中的下标。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<stdio.h> #include<Windows.h> int main() { int nums[] = { 2, 9, 11, 15 }; int target = 13; int n = sizeof(nums) / sizeof(nums[0]); int i = 0; for (i = 0; i<n; i++) { if (nums[i] < target) { int temp = nums[i]; for (int j = i+1; j < n; j++) { if (temp + nums[j] == 13) printf("i=%d j=%dn", i, j); } } } system("pause"); return 0; }

复杂度分析:

  • 时间复杂度:O(n2)O(n^2)O(n​2​​), 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n)O(n)O(n) 的时间。因此时间复杂度为 O(n2)O(n^2)O(n​2​​)。

  • 空间复杂度:O(1)O(1)O(1)。

 

 

最后

以上就是机灵夏天最近收集整理的关于LeetCode:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数的全部内容,更多相关LeetCode:给定一个整数数组和一个目标值,找出数组中和为目标值内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部