C#
 Computer >> コンピューター >  >> プログラミング >> C#

C#を使用して、指定されたターゲットに近い一意のトリプレットを見つける方法は?


Two Pointersパターンであり、Triplet SumtoZeroに似ています。同様のアプローチに従って、一度に1つの数値を取得して、配列を反復処理できます。すべてのステップで、トリプレットとターゲット数の差を保存し、各ステップでこれまでの最小ターゲット差と比較して、最終的に最も近い合計でトリプレットを返すことができるようにします。

時間計算量

配列の並べ替えにはO(N * logN)が必要です。全体として、threeSumClosest()はO(N * logN + N ^ 2)を取ります。これは、漸近的にO(N ^ 2)と同等です。

スペースの複雑さ

上記のアルゴリズムのスペースの複雑さは、ソートに必要なO(N)になります。

public class Arrays{
   public int ThreeSumClosest(int[] num, int target){
      if (num == null || num.Length == 0){
         return -1;
      }
      int[] nums = num.OrderBy(x => x).ToArray();
      int initialclosest = nums[0] + nums[1] + nums[2];
      for (int i = 0; i < nums.Count(); i++){
         int left = i + 1;
         int right = nums.Length - 1;
         while (left < right){
            int newClosest = nums[i] + nums[left] + nums[right];
            if (Math.Abs(newClosest - target) < Math.Abs(initialclosest - target)){
               initialclosest = newClosest;
            }
            if (newClosest == target){
               return newClosest;
            }
            else if (newClosest < target){
               left++;
            }
            else
            {
               right--;
            }
         }
      }
      return initialclosest;
   }
}

static void Main(string[] args){
   Arrays s = new Arrays();
   int[] nums = { -1, 2, 1, -4 };
   Console.WriteLine(s.ThreeSumClosest(nums, 1));
}

出力

2

  1. Pythonを使用して特定の年の最初のデートを見つける方法は?

    このプログラムでは、年の最初の日を印刷する必要があります。ユーザー入力として1年かかる必要があります。 アルゴリズム Step 1: Import the datetime library. Step 2: Take year as input from the user. Step 3: Get the first day of the year by passing month, day and year as parameters to the datetime.datetime() function Step 4: Display the first day using strftim

  2. Pythonを使用して特定の数値の桁数を見つける方法は?

    このプログラムでは、ユーザーが指定した整数の桁数を見つける必要があります。 例 ユーザー入力:123、出力:3 ユーザー入力:1987、出力:4 アルゴリズム Step 1: Take Integer value as input value from the userStep 2: Divide the number by 10 and convert the quotient into Integer typeStep 3: If quotient is not 0, update count of digit by 1Step 4: If quotient is 0, stop