LeetCode百日筑基系列主要是为了练习基础的数据结构与算法,题库全为LeetCode简单题(后面会在其他系列更新中等题和困难题),主要使用C语言和Java编写,前期的题目以完成功能为目的,后续会使用更优的算法以及优化代码块。
1.两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
C语言
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int i, j;
for(i = 0; i < numsSize-1; i++){
for(j = i+1; j < numsSize; j++){
if(nums[i] + nums[j] == target){
int *returnsum = malloc(sizeof(int)*2);
returnsum[0] = i, returnsum[1] = j;
*returnSize = 2;
return returnsum;
}
}
}
*returnSize = 0;
return NULL;
}
malloc是一个函数,这个函数主要用于动态分配内存
malloc用法:
指针名=(数据类型)malloc(长度),(数据类型)表示指针.
举例1:int *returnsum = malloc(sizeof(int)*2);
malloc开辟了一个int类型,2个int大小的空间,并且指针returnsum指向这个malloc所开辟的空间。
在使用malloc开辟空间时,使用完成一定要释放空间,如果不释放会造内存泄漏。(free)
java
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return new int[] {i,j};
}
}
}
return new int[0];
}
}
都使用暴力破解暴力算法时间复杂度O(n²),空间复杂度O(1)
两个循环,第一个循环从前到后取出一个数nums[i],第二个循环寻找target - nums[i]是否在剩下的元素中。若在,则取出。