程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 【LeetCode OJ 016】3Sum Closest

【LeetCode OJ 016】3Sum Closest

編輯:C++入門知識

【LeetCode OJ 016】3Sum Closest


題目:Given an arraySofnintegers, find three integers inSsuch that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

 For example, given array S = {-1 2 1 -4}, and target = 1.

 The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解題思路:先對數組進行排序,然後遍歷數組,尋找和最接近target的數。示例代碼:
import java.util.Arrays;
public class Solution
{
    public int threeSumClosest(int[] nums, int target)
    {
    	int length=nums.length;
    	int minNum=Integer.MAX_VALUE;
    	int tempsubNum=Integer.MAX_VALUE; 
    	Arrays.sort(nums);//先對nums進行排序
    	for(int i=0;i

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved