[Leetcode][016] 3Sum Closest (Java)

來源:互聯網
上載者:User

標籤:

題目: https://leetcode.com/problems/3sum-closest/

【標籤】Array; Two Pointers

【個人分析】

  這道題和它的姊妹題 3Sum 非常類似, 就不再多說了,具體一些的分析可以參考 [Leetcode][015] 3Sum

 

 1 public class Solution { 2     public int threeSumClosest(int[] nums, int target) { 3         int result = target; 4         int len = nums.length; 5         if (len < 3) { 6             return 0; 7         } 8         Arrays.sort(nums); 9         for (int i = 0; i < len; i++) {10             int number = nums[i];11             12             int leftIndex = i + 1;13             int rightIndex = len - 1;14             while (leftIndex < rightIndex) {15                 int threeSum = number + nums[leftIndex] + nums[rightIndex];16                 if (threeSum == target) {17                     // best result found!18                     return target;19                 } else {20                     // update global result21                     if ( result == target || 22                             Math.abs(target - threeSum) < Math.abs(target - result)) {23                         result = threeSum;24                     }25                     if (threeSum < target) {26                         while (leftIndex < rightIndex && 27                                 nums[leftIndex] == nums[leftIndex + 1]) {28                             leftIndex++;29                         }30                         leftIndex++;31                     } else {32                         while (leftIndex < rightIndex && 33                                 nums[rightIndex] == nums[rightIndex - 1]) {34                             rightIndex--;35                         }36                         rightIndex--;37                     }38                 }39             }40         }41         return result;42     }43 44 }

 

[Leetcode][016] 3Sum Closest (Java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.