剑指offer--和为s的数字

题目描述🍗

输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数字的和等于s,则输出任意一对即可。

算法分析🍗

算法1:遍历所有的数字,查看其它(后面所有的)数字和当前数字相加是否为s。O(n^2)

cpp 复制代码
//arr:数组起始地址
//len:数组长度
//s:需要的和
void SumTos(int* arr, int len, int s)//O(n^2)
{
    for (int i = 0; i < len; i++)//遍历所有数字
    {
        for (int j = i + 1; j < len; j++)//遍历i后面所有的数字
        {
            if (arr[i] + arr[j] == s)
                printf("%d+%d=%d\n",arr[i],arr[j],s);
        }
    }
}

int main()
{
    int arr[] = {1,2,4,7,8,11,15};
    int len = sizeof(arr) / sizeof(arr[0]);
    int s = 15;
    SumTos(arr,len,s);

    return 0;
}

算法2.利用数据有序,用两个下标,一个在最前面,另一个在最后面,两个值相加如果等于s即找到,如果小于s则前面的下标往后移,如果大于s则后面的下标前移。

cpp 复制代码
//arr:数组起始地址
//len:数组长度
//s:需要的和
void SumTos(int* arr, int len, int s)//O(n)
{
    int low = 0;
    int high = len - 1;
    int sum;//和
    while (low < high)//输出所有和为s的数字
    {
        sum = arr[low] + arr[high];
        if (sum == s)
        {
            printf("%d+%d=%d\n", arr[low], arr[high], s);
            low++;
        }

        else if (sum < s)//low后移
            low++;
        else //sum>s ,high前移
            high--;
    }
}

int main()
{
    int arr[] = {1,2,4,7,8,11,15};
    int len = sizeof(arr) / sizeof(arr[0]);
    int s = 15;
    SumTos(arr,len,s);

    return 0;
}

本篇完!🍗

相关推荐
m0_547486661 天前
《数据结构教程》全套 PPT课件2026
数据结构
旖旎夜光1 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
CoderYanger2 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
圣保罗的大教堂2 天前
leetcode 3524. 求出数组的 X 值 I 中等
leetcode
Tim_102 天前
【LeetCode】338、比特位计数
c++·算法·leetcode
tryxr2 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.2 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
开开心心就好2 天前
安卓手写文字生成工具,多种纸张一直免费
网络·网络协议·tcp/ip·leetcode·智能手机·电脑·模拟退火算法