1588. 所有奇数长度子数组的和
给你一个正整数数组 arr ,请你计算所有可能的奇数长度子数组的和。
子数组 定义为原数组中的一个连续子序列。
请你返回 arr 中 所有奇数长度子数组的和 。
输入:arr = [1,4,2,5,3]
输出:58
解释:所有奇数长度子数组和它们的和为:
[1] = 1
[4] = 4
[2] = 2
[5] = 5
[3] = 3
[1,4,2] = 7
[4,2,5] = 11
[2,5,3] = 10
[1,4,2,5,3] = 15
我们将所有值求和得到 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
我的方法:暴力法,外层l的长度从1依次加二,中层起始下标控制start+length<数组长,内层子数组从start到start+length
class Solution {
public int sumOddLengthSubarrays(int[] arr) {
int sum = 0;
for(int l=1;l<=arr.length;l+=2){
for(int i=0;i<=arr.length-l;i++){
for(int j=0;j<l;j++){
sum+=arr[i+j];
}
}
}
return sum;
}
}
方法二、前缀和
class Solution {
public int sumOddLengthSubarrays(int[] arr) {
int n = arr.length;
int[] prefixSums = new int[n + 1];
for (int i = 0; i < n; i++) {
prefixSums[i + 1] = prefixSums[i] + arr[i];
}
int sum = 0;
for (int start = 0; start < n; start++) {
for (int length = 1; start + length <= n; length += 2) {
int end = start + length - 1;
sum += prefixSums[end + 1] - prefixSums[start];
}
}
return sum;
}
}
方法三、数学方法
class Solution {
public int sumOddLengthSubarrays(int[] arr) {
int sum = 0;
int n = arr.length;
for (int i = 0; i < n; i++) {
int leftCount = i, rightCount = n - i - 1;
int leftOdd = (leftCount + 1) / 2;
int rightOdd = (rightCount + 1) / 2;
int leftEven = leftCount / 2 + 1;
int rightEven = rightCount / 2 + 1;
sum += arr[i] * (leftOdd * rightOdd + leftEven * rightEven);
}
return sum;
}
}
953. 验证外星语词典
某种外星语也使用英文小写字母,但可能顺序 order 不同。字母表的顺序(order)是一些小写字母的排列。
给定一组用外星语书写的单词 words,以及其字母表的顺序 order,只有当给定的单词在这种外星语中按字典序排列时,返回 true;否则,返回 false。
示例:
输入:words = [“hello”,“leetcode”], order = “hlabcdefgijkmnopqrstuvwxyz”
输出:true
解释:在该语言的字母表中,‘h’ 位于 ‘l’ 之前,所以单词序列是按字典序排列的。
class Solution {
public boolean isAlienSorted(String[] words, String order) {
int[] index = new int[26];
for (int i = 0; i < order.length(); ++i)
index[order.charAt(i) - 'a'] = i;
search: for (int i = 0; i < words.length - 1; ++i) {
String word1 = words[i];
String word2 = words[i+1];
// Find the first difference word1[k] != word2[k].
for (int k = 0; k < Math.min(word1.length(), word2.length()); ++k) {
if (word1.charAt(k) != word2.charAt(k)) {
// If they compare badly, it's not sorted.
if (index[word1.charAt(k) - 'a'] > index[word2.charAt(k) - 'a'])
return false;
continue search;
}
}
// If we didn't find a first difference, the
// words are like ("app", "apple").
if (word1.length() > word2.length())
return false;
}
return true;
}
}
206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}