LeetCode 题库1. 两数之和 答案及笔记
2018-08-22 22:55
15 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/deadgodpb/article/details/81952496
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
答案:
[code]/** * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target) { int i,j; int *new=malloc(sizeof(int)*2); for(i=0;i<numsSize;i++) { for(j=i+1;j<numsSize;j++) { if(((nums[i]+ nums[j])==target)&&(i!=j)) { if(i>j) { new[0]=j; new[1]=i; } else { new[0]=i; new[1]=j; } return new; } } } return new; }
笔记:错误1:函数内定义 int new[2] ,不可以直接return new, 返回的指针在函数返回后会被释放,需要分配动态内存。
错误2:审题忽略了同一个元素不能重复利用。
相关文章推荐
- LeetCode刷题笔记之1:两数之和Python
- 哈希表学习笔记及LeetCode编程练习之两数之和and快乐数
- Leetcode题库-两数之和 II - 输入有序数组(java语言版)
- Leetcode题库-两数之和(java语言版)
- leetcode刷题笔记-两数相加(1)
- Leetcode刷题笔记 两数之和
- leetcode笔记—二进制数中1的个数
- LeetCode刷题笔记342:4的幂(Python实现)
- leetcode的python实现 刷题笔记35:搜索插入位置的暴力解法和优化解法
- 《C++编程思想》(第二版)第3章 C++中的C(笔记、习题及答案)(二)
- 小白笔记------------------------------------leetcode(389. Find the Difference )
- 超星尔雅答案题库
- [LeetCode] 1. Two Sum 两数和
- Leetcode题库 - 验证回文串(java语言版)
- leetcode的python实现 刷题笔记53:最大子序和(多种解法)
- LeetCode刷题笔记 442. 数组中重复的数据
- leetcode笔记-Path Sum
- LeetCode解题笔记349 Intersection of Two Arrays
- leetcode的python实现 刷题笔记70:爬楼梯(动态规划)
- LeetCode1 两数之和 Two Sum