voidsort(int* nums,int numsSize){for(int i =0;i < numsSize;i++){for(int j =0;j < numsSize - i -1;j++){if(nums[j]> nums[j +1]){int tmp = nums[j];nums[j]= nums[j +1];nums[j +1]= tmp;}}}}inttriangleNumber(int* nums,int numsSize){int count =0;int right = numsSize -1;//1.排序sort(nums,numsSize);//2.循环判断是否固定一个值结束while(right >=2){//当元素个数小于2个则无法进行判断int left =0;int tmp = right -1;while(tmp > left){if(nums[tmp]+ nums[left]> nums[right]){//判断是否有效三角形count += tmp - left;tmp--;}else{left++;}}right--;//改变外层循环}//3.循环判断是否为三角形return count;}
JAVA代码如下:
classSolution{publicinttriangleNumber(int[] nums){Arrays.sort(nums);int count =0;int i = nums.length -1;while(i >=2){int left =0;int right = i -1;while(left < right){if(nums[left]+ nums[right]> nums[i]){count += right - left;right--;}else{left++;}}i--;}return count;}}