No. 09 - Numbers with a Given Sum

No. 09 - Numbers with a Given Sum


Problem 1: Given an increasingly sorted array and a number s, please find two numbers whose sum is s. If there are multiple pairs with sum s, just output any one of them.

For example, if the inputs are an array  { 1 2 4 7 11 15} and a number 15, please out two numbers 4 and 11 since 4+11=15.

Analysis: Let us firstly have a try to select two numbers (denoted as num1 and num2) of the input array. If their sum equals to s, we are fortunate because the required numbers have been found. If the sum is less than s, we may replace num1 with its next number, because the array is increasingly sorted and its next number should be greater. If the sum is greater than s, num2 can be replaced with its previous number in the sorted array, which should be less than num2.

Take the array  { 1 2 4 7 11 15} and number 15 as an example. We define two pointers. At the first step, they point to the first number (also the least one) 1 and the last number (also the greatest one) 15. We move the second pointer forward to number 11, since their sum 16 and it is greater than 15.

At the second step, the two numbers are 1 and 11, and their sum 12 is less than 15. Therefore, we can move the first pointer afterward and let it point to 2.

The two numbers are 2 and 11 accordingly at the third step. Since their sum 13 is less than 15, we move the first pointer afterward again.

Now the two numbers are 4 and 11, and their sum is 15 which is the expected sum. Therefore, we have found two numbers whose sum is 15.

The process is summarized as in Table 1:

Step
Num1
Num2
Sum
Comparing with s
Operation
1
1
15
16
Greater
Select the previous number of Num2
2
1
11
12
Less
Select the next number of Num1
3
2
11
13
Less
Select the next number of Num1
4
4
11
15
Equal

Table 1: Find a pair of numbers with sum 15 out of array {1、2、4、7、11、15}

After interviewers approve our solution, we can begin to write code. The following is a piece of sample code:

bool FindNumbersWithSum( int data[],  int length,  int sum,
                         int* num1,  int* num2)
{
     bool found =  false;
     if(length < 1 || num1 == NULL || num2 == NULL)
         return found;

     int ahead = length - 1;
     int behind = 0;

     while(ahead > behind)
    {
         long  long curSum = data[ahead] + data[behind];

         if(curSum == sum)
        {
            *num1 = data[behind];
            *num2 = data[ahead];
            found =  true;
             break;
        }
         else  if(curSum > sum)
            ahead --;
         else
            behind ++;
    }

     return found;
}

In the code above, ahead is the index of the first number, and behind is the index of the second number. Since we only need to scan the input array once, its time complexity is O(n).

Problem 2: Given an array, please determine whether it contains three numbers whose sum equals to 0.

Analysis: This problem is also required to find some numbers with a given array and sum, it is similar to the first problem. We may get some hints from the solution above.

Since the input of the previous problem is an increasingly sorted array, we can also firstly sort the input array increasingly. Secondly we scan the array. When we reach the i-th number with value n, we try to find whether there are two numbers whose sum is –n in the array excluding the i-th number.

It is time for us to write some code. We modify the function FindNumbersWithSum above a little bit:

bool FindNumbersWithSum( int data[],  int length,  int sum,  int excludeIndex)
{
     bool found =  false;
     int ahead = length - 1;
     int behind = 0;

     while(ahead > behind)
    {
         if(ahead == excludeIndex)
            ahead --;
         if(behind == excludeIndex)
            behind ++;

         long  long curSum = data[ahead] + data[behind];

         if(curSum == sum)
        {
            found =  true;
             break;
        }
         else  if(curSum > sum)
            ahead --;
         else
            behind ++;
    }

     return found;
}
It determines whether there are two numbers whose sum is sum in array data excluding the number with index excludeIndex. We can determine whether there are three numbers in an array with sum 0 based on this function:
bool HasThreeNumbersWithSum0( int data[],  int length)
{
     bool found =  false;
     if(data == NULL || length < 3)
         return found;

    std::sort(data, data + length - 1);

     for( int i = 0; i < length; ++i)
    {
         int sum = -data[i];
         int num1, num2;
        found = FindNumbersWithSum(data, length, sum, i);

         if(found)
             break;
    }

     return found;
}

It contains two steps in function HasThreeNumbersWithSum0. It costs O(n logn)time to sort n numbers at its first step. At its second step it costs O(n) time for each number to callFindNumberWithSum, so it costs O(n 2) time in the for loop. Therefore, its overall time complexity is O(n 2).

The author Harry He owns all the rights of this post. If you are going to use part of or the whole of this ariticle in your blog or webpages,  please add a reference to  http://codercareer.blogspot.com/. If you are going to use it in your books, please contact me (zhedahht@gmail.com) . Thanks.

C. XOR-factorization time limit per test2 seconds memory limit per test256 megabytes    Ostad thinks that the usual way of factoring numbers is too mathematical, so he invented a new notion called XOR-factorization, which is more computer-science-like. For a given integer n , a sequence of integers a1,a2,…,ak with 0≤ai≤n for all i is called a XOR-factorization of n if and only if a1&oplus;a2&oplus;⋯&oplus;ak=n, where &oplus; denotes the bitwise XOR operation. You are given integers n and k . Find a XOR-factorization a1,a2,…,ak of n that maximizes the sum a1+a2+⋯+ak . It can be proven that under the problem conditions, a XOR-factorization always exists. DeepL 翻译    奥斯塔德认为通常的因式分解方法过于数学化,因此他发明了一种新的概念,称为 XOR 因式分解,这种方法更类似于计算机科学。对于给定的整数 n ,当且仅当符合以下条件时,所有 i 的整数 a1,a2,…,ak 与 0≤ai≤n 的序列称为 n 的 XOR 因式分解 a1&oplus;a2&oplus;⋯&oplus;ak=n, 其中 &oplus; 表示位向 XOR 运算。 给定整数 n 和 k 。请找出使总和 a1+a2+⋯+ak 最大的 n 的 XOR 因式分解 a1,a2,…,ak 。 可以证明,在问题条件下,XOR 因式分解总是存在的。    Input Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤104 ). The description of the test cases follows. Each of the next t lines contains two integers n and k (1≤n≤109 , 1≤k≤105 ). It is guaranteed that the sum of k over all test cases does not exceed 105 . DeepL 翻译    输入 每个测试包含多个测试用例。第一行包含测试用例的数量 t ( 1≤t≤104 )。测试用例说明如下。 接下来的每行 t 包含两个整数 n 和 k ( 1≤n≤109 , 1≤k≤105 )。 保证所有测试用例中 k 的总和不超过 105 。    Output For each test case, output k integers a1,a2,…,ak such that 0≤ai≤n . We can show that an answer always exists. If there are multiple valid answers, you may print any of them in any order. DeepL 翻译    输出 对于每个测试用例,输出 k 个整数 a1,a2,…,ak ,使得 0≤ai≤n . 我们可以证明答案总是存在的。如果存在多个有效答案,可以按任意顺序打印其中任何一个。 Example InputCopy 4 5 4 4 3 8 2 1 1 OutputCopy 1 4 5 5 4 4 4 0 8 1    Note In the first test case, we can factor 5 as 1&oplus;4&oplus;5&oplus;5 with a sum of 15 , and it can be shown that no other XOR-factorization has a higher sum. In the second test case, we can factor 4 as 4&oplus;4&oplus;4 with a sum of 12 , which is trivially the maximum possible.用c++
12-21
【电力系统】单机无穷大电力系统短路故障暂态稳定Simulink仿真(带说明文档)内容概要:本文档围绕“单机无穷大电力系统短路故障暂态稳定Simulink仿真”展开,提供了完整的仿真模型与说明文档,重点研究电力系统在发生短路故障后的暂态稳定性问题。通过Simulink搭建单机无穷大系统模型,模拟不同类型的短路故障(如三相短路),分析系统在故障期间及切除后的动态响应,包括发电机转子角度、转速、电压和功率等关键参数的变化,进而评估系统的暂态稳定能力。该仿真有助于理解电力系统稳定性机理,掌握暂态过程分析方法。; 适合人群:电气工程及相关专业的本科生、研究生,以及从事电力系统分析、运行与控制工作的科研人员和工程师。; 使用场景及目标:①学习电力系统暂态稳定的基本概念与分析方法;②掌握利用Simulink进行电力系统建模与仿真的技能;③研究短路故障对系统稳定性的影响及提高稳定性的措施(如故障清除时间优化);④辅助课程设计、毕业设计或科研项目中的系统仿真验证。; 阅读建议:建议结合电力系统稳定性理论知识进行学习,先理解仿真模型各模块的功能与参数设置,再运行仿真并仔细分析输出结果,尝试改变故障类型或系统参数以观察其对稳定性的影响,从而深化对暂态稳定问题的理解。
本研究聚焦于运用MATLAB平台,将支持向量机(SVM)应用于数据预测任务,并引入粒子群优化(PSO)算法对模型的关键参数进行自动调优。该研究属于机器学习领域的典型实践,其核心在于利用SVM构建分类模型,同时借助PSO的全局搜索能力,高效确定SVM的最优超参数配置,从而显著增强模型的整体预测效能。 支持向量机作为一种经典的监督学习方法,其基本原理是通过在高维特征空间中构造一个具有最大间隔的决策边界,以实现对样本数据的分类或回归分析。该算法擅长处理小规模样本集、非线性关系以及高维度特征识别问题,其有效性源于通过核函数将原始数据映射至更高维的空间,使得原本复杂的分类问题变得线性可分。 粒子群优化算法是一种模拟鸟群社会行为的群体智能优化技术。在该算法框架下,每个潜在解被视作一个“粒子”,粒子群在解空间中协同搜索,通过不断迭代更新自身速度与位置,并参考个体历史最优解和群体全局最优解的信息,逐步逼近问题的最优解。在本应用中,PSO被专门用于搜寻SVM中影响模型性能的两个关键参数——正则化参数C与核函数参数γ的最优组合。 项目所提供的实现代码涵盖了从数据加载、预处理(如标准化处理)、基础SVM模型构建到PSO优化流程的完整步骤。优化过程会针对不同的核函数(例如线性核、多项式核及径向基函数核等)进行参数寻优,并系统评估优化前后模型性能的差异。性能对比通常基于准确率、精确率、召回率及F1分数等多项分类指标展开,从而定量验证PSO算法在提升SVM模型分类能力方面的实际效果。 本研究通过一个具体的MATLAB实现案例,旨在演示如何将全局优化算法与机器学习模型相结合,以解决模型参数选择这一关键问题。通过此实践,研究者不仅能够深入理解SVM的工作原理,还能掌握利用智能优化技术提升模型泛化性能的有效方法,这对于机器学习在实际问题中的应用具有重要的参考价值。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值