- 题目描述:
- 题目链接:
-视频讲解链接B站视频讲解
- 复杂度分析:
- 代码:
c++版本:
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求最小差值
* @param a int整型vector 数组a
* @return int整型
*/
int minDifference(vector<int>& a) {
// write code here
sort(a.begin(),a.end());
long long res = a[1] - a[0];
for(int i = 2;i < a.size();i ++){
if((long long)(a[i] - a[i-1]) < res){
res = (long long)(a[i] - a[i-1]);
}
}
return (int)res;
}
};
Java版本:
import java.util.*;
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求最小差值
* @param a int整型一维数组 数组a
* @return int整型
*/
public int minDifference (int[] a) {
// write code here
Arrays.sort(a);//排序
long res = (long)a[1] -(long) a[0];
for(int i = 2; i < a.length; i++) {
if((long)a[i] - (long)a[i - 1] < res) {
res = (long)a[i] - (long)a[i - 1];
}
}
return (int)res;
}
}Python版本:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
# 求最小差值
# @param a int整型一维数组 数组a
# @return int整型
#
class Solution:
def minDifference(self , a ):
# write code here
a.sort()
res = a[1] - a[0]
for i in range(2,len(a)):
if res > (a[i] - a[i-1]):
res = a[i] - a[i-1]
return resJavaScript版本:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 求最小差值
* @param a int整型一维数组 数组a
* @return int整型
*/
function minDifference( a ) {
// write code here
a.sort((a,b)=>a-b);
let res = a[1] - a[0];
for(let i = 2; i < a.length; i++) {
if(a[i] - a[i - 1] < res) {
res = a[i] - a[i - 1];
}
}
return res;
}
module.exports = {
minDifference : minDifference
};
京公网安备 11010502036488号