Java solution similar idea to O(n^2) 3Sum


  • 0
    J
    public class Solution {
        public int triangleNumber(int[] nums) {
            Arrays.sort(nums);
            int count = 0;
            for (int i = 0; i < nums.length - 2; i++) {
                int first = nums[i];
                for (int p = i + 1, q = i + 2; p < nums.length - 1; p++) {
                    while (p == q || q < nums.length && nums[q] - nums[p] < first) {
                        q++;
                    }
                    count += q - p - 1;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.