java如何找到中心
查找数组的中心索引
在Java中,查找数组的中心索引可以通过计算数组左右两边的和来实现。中心索引的定义是数组的某个索引,使得索引左侧所有元素的和等于右侧所有元素的和。

public int pivotIndex(int[] nums) {
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
int leftSum = 0;
for (int i = 0; i < nums.length; i++) {
if (leftSum == totalSum - leftSum - nums[i]) {
return i;
}
leftSum += nums[i];
}
return -1;
}
查找链表的中间节点
对于链表,可以使用快慢指针法来找到中间节点。快指针每次移动两步,慢指针每次移动一步,当快指针到达链表末尾时,慢指针指向的就是中间节点。

public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
查找二维数组的中心
对于二维数组,中心可以通过行数和列数的中间值来确定。如果行数或列数为偶数,则可能没有确切的中心。
public int[] findCenter(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
if (rows % 2 == 0 || cols % 2 == 0) {
return null; // 没有确切中心
}
return new int[]{rows / 2, cols / 2};
}
查找字符串的中心字符
对于字符串,如果长度为奇数,中心字符就是中间的那个字符;如果长度为偶数,中心字符可以是中间的两个字符。
public String findCenterChar(String s) {
int length = s.length();
if (length % 2 == 1) {
return s.substring(length / 2, length / 2 + 1);
} else {
return s.substring(length / 2 - 1, length / 2 + 1);
}
}
注意事项
- 对于数组和链表,确保处理边界条件,如空数组或空链表。
- 在计算和或移动指针时,注意索引越界问题。
- 对于二维数组或字符串,明确中心定义,尤其是在偶数长度情况下。






