1. Two Sum
来源:互联网 发布:sal绘画软件 sai 编辑:程序博客网 时间:2024/05/22 21:24
问题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
解题思路:
先开辟一个2个int空间的数组a用来存放满足要求的整数的下标。
使用双层for循环遍历nums数组,将两两之和与target比较,如果相等则将两个数的下标存放进数组a并返回。
C语言解题代码/** * Note: The returned array must be malloced, assume caller calls free(). */int* twoSum(int* nums, int numsSize, int target) { int (*a)[2]; a=calloc(2,sizeof(int)); for(int i=0;i<numsSize;i++) { (*a)[0]=i; for(int j=i+1;j<numsSize;j++) { (*a)[1]=j; if(target==nums[i]+nums[j]) return a; } } return 0;}
体会:
本题解题方法简单,难点在与c语言无法直接返回数组, 所以做题时被卡在了返回数组的问题上。解决方法是采用指针来传递。
声明了一个指针之后还需要为其开辟一个内存空间。
算是复习了一下数组和指针两方面的知识。
0 0
- 1. Two Sum && 167. Two Sum II
- LeetCode 1. Two Sum
- [LeetCode]1.Two Sum
- LeetCode 1.Two Sum
- LeetCode --- 1. Two Sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- leetcode---1.Two sum
- 1.Two Sum
- [Leetcode] 1. Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1. Two Sum
- 1. Two Sum Ruby
- LeetCode 1.Two Sum
- LeetCode 1.Two Sum
- 1. Two Sum
- 1.Two Sum
- 1049. 数列的片段和
- leetcode 516. Longest Palindromic Subsequence
- 负载均衡分类
- 【OpenCV学习笔记】八、鼠标与滑动条操作
- Eclipse4.4以上版本不能使用easyExplorer,采用OpenExplorer
- 1. Two Sum
- Callable与Future的介绍
- Android Studio的下载安装及配置
- 京东和淘宝
- Hexo 添加站内搜索
- Nginx/LVS/HAProxy负载均衡软件的优缺点详解(总结)
- 大数据学习——NoSQL分布式数据库综述
- 华为员工中年危机
- iOS学习之block