Solution_LCR012.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.sf.leetcode;
  2. public class Solution_LCR012 {
  3. public static void main(String[] args) {
  4. int[] nums = {1, 7, 3, 6, 5, 6};
  5. int pivotIndex = new Solution_LCR012().pivotIndex(nums);
  6. System.out.println(pivotIndex);
  7. }
  8. // [1,7, 3, 6, 5, 6]
  9. public int pivotIndex(int[] nums) {
  10. int n = nums.length;
  11. // 计算总和
  12. int total = 0;
  13. for (int i = 0; i < n; i++) {
  14. total += nums[i];
  15. }
  16. // total = 28
  17. // 计算元素的前缀和 是否符合要求
  18. int sum = 0;
  19. for (int i = 0; i < n; i++) {
  20. // 0 1 8 11 17 22 28
  21. // 后面元素之和 = 所有元素之和 - 自身 - 前面元素之和
  22. // 11 = 28 - 6 - 11
  23. if (sum == total - nums[i] - sum) {
  24. return i;
  25. }
  26. sum += nums[i];
  27. }
  28. // 找不到符合条件的索引
  29. return -1;
  30. }
  31. // 使用正序和 和 逆序和 计算
  32. public int pivotIndex1(int[] nums) {
  33. int n = nums.length;
  34. int[] sort = new int[n + 1];
  35. int[] reSort = new int[n + 1];
  36. for (int i = 1; i <= n; i++) {
  37. // sort[1] = sort[0] + nums[0]
  38. sort[i] = sort[i - 1] + nums[i - 1];
  39. }
  40. int index = -1;
  41. if (reSort[n - 1] == sort[n - 1]) {
  42. index = n - 1;
  43. }
  44. for (int i = n - 2; i >= 0; i--) {
  45. // reSort[n-2] = reSort[n-1] + nums[n-1];
  46. reSort[i] = reSort[i + 1] + nums[i + 1];
  47. if (reSort[i] == sort[i]) {
  48. index = i;
  49. }
  50. }
  51. // for (int i = 0; i < n; i++) {
  52. // if (sort[i] == reSort[i]) {
  53. // return i;
  54. // }
  55. // }
  56. return index;
  57. }
  58. }