Triangle Count
Given an array of integers, how many three numbers can be found in the array, so that we can build an triangle whose three edges length is the three numbers that we find?
Example
Given array S = [3,4,6,7], return 3. They are:
[3,4,6]
[3,6,7]
[4,6,7]
Given array S = [4,4,4,4], return 4. They are:
[4(1),4(2),4(3)]
[4(1),4(2),4(4)]
[4(1),4(3),4(4)]
[4(2),4(3),4(4)]
先sort 然后对于每一个元素i 利用左右双index扫面0到i-1 找出符合条件的元素对
1 public class Solution { 2 /** 3 * @param S: A list of integers 4 * @return: An integer 5 */ 6 public int triangleCount(int S[]) { 7 Arrays.sort(S); 8 int count = 0; 9 for (int i = 0; i < S.length; i++) { 10 int left = 0; 11 int right = i - 1; 12 while (left < right) { 13 if (S[left] + S[right] > S[i]) { 14 // The edge from S[left] to S[right - 1] will also form a triangle 15 count += right - left; 16 right--; 17 } else { 18 left++; 19 } 20 } 21 } 22 return count; 23 } 24 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步