leetcode 1 two sum 刷题学习笔记

xiaoxiao2021-02-28  44

本类博客用来记录分享自己在 LeetCode 刷题过程中的的问题以及学到的技巧等!

第一题 Two sum

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].

思路:我的思路就是通过两个 for循环,穷举法来获得结果。

/** * Note: The returned array must be malloced, assume caller calls free(). */ int* twoSum(int* nums, int numsSize, int target) { int i,j; int *a; a=(int *)malloc(sizeof(int)*2);//申请内存空间,大小为2个int长度。 for(i=0;i<=numsSize-1;i++) { for(j=i+1;j<=numsSize-1;j++) {if(target==(*(nums+i)+*(nums+j))) { *a=i; *(a+1)=j; break;}} } return a; }

转载请注明原文地址: https://www.6miu.com/read-27614.html

最新回复(0)