当前位置:网站首页>leetcode刷题_两数之和 II - 输入有序数组
leetcode刷题_两数之和 II - 输入有序数组
2022-07-03 01:05:00 【身影王座】
题目描述
java解决方法
class Solution {
public int[] twoSum(int[] numbers, int target) {
int index1 = 0;
int index2 = numbers.length - 1;
int[] index = new int[2];
while(index1 < index2)
{
if(numbers[index2] + numbers[index1] > target)
{
index2--;
}
else if(numbers[index2] + numbers[index1] < target)
{
index1++;
}
else
{
index[0] = index1 + 1;
index[1] = index2 + 1;
break;
}
}
return index;
}
}
C解决方法
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){
int *index = NULL;
int index1 = 0;
int index2 = numbersSize - 1;
index = (int*)malloc(2 * sizeof(int));
while(index1 < index2)
{
if(numbers[index1] + numbers[index2] > target)
{
index2--;
}
else if(numbers[index1] + numbers[index2] < target)
{
index1++;
}
else
{
index[0] = index1 + 1;
index[1] = index2 + 1;
break;
}
}
*returnSize = 2;
return index;
}
返回回去的变量一定要动态开辟内存,因为局部变量保存在栈上,随着函数的生命周期的结束会内存销毁,而动态开辟的内存是在堆上,函数结束,并不会释放该内存。
边栏推荐
- 12_ Implementation of rolling automatic video playback effect of wechat video number of wechat applet
- 2022 cable crane driver examination registration and cable crane driver certificate examination
- 数学知识:Nim游戏—博弈论
- Basic remote connection tool xshell
- Button wizard play strange learning - automatic return to the city route judgment
- 一比特苦逼程序員的找工作經曆
- 音程的知识的总结
- 【第29天】给定一个整数,请你求出它的因子数
- Database SQL language 01 where condition
- ThinkPHP+Redis实现简单抽奖
猜你喜欢
一比特苦逼程序員的找工作經曆
【C语言】指针与数组笔试题详解
MySQL foundation 04 MySQL architecture
MySQL basics 03 introduction to MySQL types
[fh-gfsk] fh-gfsk signal analysis and blind demodulation research
【面试题】1369- 什么时候不能使用箭头函数?
Expérience de recherche d'emploi d'un programmeur difficile
【无标题】
【FPGA教程案例6】基于vivado核的双口RAM设计与实现
[flutter] icons component (fluttericon Download Icon | customize SVG icon to generate TTF font file | use the downloaded TTF icon file)
随机推荐
MySQL foundation 05 DML language
Druid database connection pool
信息熵的基础
看完这篇 教你玩转渗透测试靶机Vulnhub——DriftingBlues-9
给你一个可能存在 重复 元素值的数组 numbers ,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。【剑指Offer】
What operations need attention in the spot gold investment market?
d,ldc構建共享庫
不登陆或者登录解决oracle数据库账号被锁定。
数学知识:台阶-Nim游戏—博弈论
Mathematical Knowledge: Steps - Nim Games - Game Theory
The difference between tail -f, tail -f and tail
LDC Build Shared Library
Embrace the safety concept of platform delivery
Kivy教程大全之如何在 Kivy 中创建下拉列表
leetcode:871. Minimum refueling times [Pat has done before + maximum stacking + greed]
Basic remote connection tool xshell
按键精灵打怪学习-自动寻路回打怪点
MySQL foundation 07-dcl
软考信息系统项目管理师_历年真题_2019下半年错题集_上午综合知识题---软考高级之信息系统项目管理师053
按键精灵打怪学习-多线程后台坐标识别