zoukankan      html  css  js  c++  java
  • 2010412 面试题

    给定一个整数数组,例如{2,4,5,6,7,8}和一个数字,例如10,请设计一个函数找出两个元素,并且使这两个数的和为给定数字,并答应出来。

    代码
    using System;
    using System.Collections.Generic;

    public class MyClass
    {
        
    public static void Main()
        {
            
    int[] a=new int[]{2,3,4,5,6,7,8,9};
            
    int sum=10;
            
    int n=sum/2;
            
    int nc=0;
            
    for(int i=0;i<a.Length;i++)
            {
                
    if(a[i]>n)
                {
                    nc
    =i;
                    
    break;
                }
            }
            
    if(nc==0)
            {
                Console.WriteLine(
    "没有这样的两个数字之和等于"+sum);
                
    return;
            }
            
    int nc1=nc;
            
    int nc2=nc;
            
    while(nc1>=0 && nc2<a.Length)
            {
                
    int a1=a[nc1];
                
    int a2=a[nc2];    
                
    if(a1+a2==sum)
                {
                    Console.WriteLine(a1
    +"+"+a2+"="+sum);
                    nc1
    --;
                }
                
    else if(a1+a2>sum)
                {
                    nc1
    --;
                }
                
    else if(a1+a2<sum)
                {
                    nc2
    ++;
                }
            }
            Console.ReadLine();
        }
    }


  • 相关阅读:
    get函数理解
    get函数理解
    Absolute C++ 第9章字符串 编程练习4
    Absolute C++ 第9章字符串 编程练习4
    Absolute C++ 第9章字符串 编程练习4
    Absolute C++ 第9章字符串 编程练习4
    C字符串使用陷阱 “=”和“==” 学习笔记
    [Android]ListView中分割线的设置
    如何在adapter 中调用activity的方法
    Android开发中Handler的经典总结
  • 原文地址:https://www.cnblogs.com/mikechang/p/1710500.html
Copyright © 2011-2022 走看看