【Lintcode】576. Split Array
題目地址:
https://www.lintcode.com/problem/split-array/description
給定一個長 N N N的陣列 A A A,題目保證 N ≥ 5 N\ge 5 N≥5。要求兩個數 p p p和 q q q滿足 0 < p < q < N − 1 , q − p > 1 0<p<q<N-1, q-p>1 0<p<q<N−1,q−p>1,使得 A [ p ] + A [ q ] A[p]+A[q] A[p]+A[q]最小,返回這個最小和。
求最小的三個數,如果最小的兩個數相距超過 1 1 1則返回它們的和;否則如果最小和第三小的兩個數相距超過 1 1 1則返回它們的和;否則返回第二小和第三小的數之和。程式碼如下:
public class Solution {
/**
* @param arr: an inter array
* @return: return the min sum
*/
public int splitArray(int[] arr) {
// write your code here
int min1, min2, min3, pos1, pos2, pos3;
min1 = min2 = min3 = Integer.MAX_VALUE;
pos1 = pos2 = pos3 = -1;
for (int i = 1; i < arr.length - 1; i++) {
if (arr[i] < min1) {
min3 = min2;
min2 = min1;
min1 = arr[i];
pos3 = pos2;
pos2 = pos1;
pos1 = i;
} else if (arr[i] < min2) {
min3 = min2;
min2 = arr[i];
pos3 = pos2;
pos2 = i;
} else if (arr[i] < min3) {
min3 = arr[i];
pos3 = i;
}
}
if (Math.abs(pos1 - pos2) > 1) {
return min1 + min2;
} else if (Math.abs(pos1 - pos3) > 1) {
return min1 + min3;
} else {
return min2 + min3;
}
}
}
時間複雜度 O ( N ) O(N) O(N),空間 O ( 1 ) O(1) O(1)。
相關文章
- Cat, Fox and Maximum Array Split
- 【Lintcode】1793. Balanced Sales Array
- 【Lintcode】1623. Minimal Distance In The Array
- 《每日一題》842. Split Array into Fibonacci Sequence 將陣列拆分成斐波那契序列每日一題陣列
- JavaScript split()JavaScript
- Edge Split
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- Hbase split的三種方式和split的過程
- java split用法 案例Java
- os.path.split
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- php中的chunk_split()和str_split()字串函式PHP字串函式
- Array.from和 Array.of
- array
- PHP用foreach來表達array_walk/array_filter/array_map/array_reducePHPFilter
- Array()與Array.of()方法區別
- JS Array.reduce 實現 Array.map 和 Array.filterJSFilter
- Linux基礎命令—splitLinux
- Linux基礎命令---splitLinux
- split() 函式解析 (一)函式
- [LeetCode] 776. Split BSTLeetCode
- 正規表示式 split()
- MySQL實現Split用法MySql
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】1267. Lexicographical Numbers