美文网首页
LeetCode每日一题:three sum closest

LeetCode每日一题:three sum closest

作者: yoshino | 来源:发表于2017-07-05 15:10 被阅读24次

问题描述

Given an array S of n integers, find three integers in S such 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).

问题分析

这道题只让我们返回结果,所以直接三重循环暴力求解。

代码实现

public int threeSumClosest(int[] num, int target) {
        int sum, error, result, min = Integer.MAX_VALUE;
        sum = error = result = 0;
        for (int i = 0; i < num.length; i++) {
            for (int j = i + 1; j < num.length; j++) {
                for (int k = j + 1; k < num.length; k++) {
                    sum = num[i] + num[j] + num[k];
                    error = Math.abs(target - sum);
                    if (error < min) {
                        min = error;
                        result = sum;
                    }
                }
            }
        }
        return result;
    }

相关文章

网友评论

      本文标题:LeetCode每日一题:three sum closest

      本文链接:https://www.haomeiwen.com/subject/zqjqhxtx.html