Open carloscn opened 1 year ago
static int32_t largest_number(const int32_t *array, size_t len, size_t *index)
{
int32_t ret = 0;
int32_t *buffer = NULL;
size_t *index_buffer = NULL;
size_t i = 0;
size_t j = 0;
UTILS_CHECK_PTR(array);
UTILS_CHECK_PTR(index);
UTILS_CHECK_LEN(len);
buffer = (int32_t *)calloc(sizeof(int32_t), len);
UTILS_CHECK_PTR(buffer);
index_buffer = (size_t *)calloc(sizeof(size_t), len);
UTILS_CHECK_PTR(index_buffer);
memcpy(buffer, array, len * sizeof(int32_t));
for (i = 0; i < len; i ++) {
index_buffer[i] = i;
}
for (i = 0; i < len; i ++) {
for (j = 0; j < len - i - 1; j ++) {
if (buffer[j] < buffer[j + 1]) {
utils_swap_int32(buffer + j, buffer + j + 1);
utils_swap_size_t(index_buffer + j, index_buffer + j + 1);
}
}
}
if (buffer[0] >= buffer[1] * 2) {
*index = index_buffer[0];
} else {
*index = ~0;
}
finish:
UTILS_SAFE_FREE(buffer);
UTILS_SAFE_FREE(index_buffer);
return ret;
}
int32_t main(void)
{
int32_t ret = 0;
int32_t array[] = {3,1,6,0};
size_t index = 0;
ret = largest_number(array, ARRAY_SIZE(array), &index);
UTILS_CHECK_RET(ret);
LOG("The result is %zx\n", index);
finish:
return ret;
}
fn larget_number(array:&[i64]) -> Result<usize, &'static str>
{
let mut index:usize = 0;
let len:usize = array.len();
let mut buffer:Vec<i64> = Vec::new();
let mut index:Vec<usize> = Vec::new();
let mut i:usize = 0;
let mut j:usize = 0;
if 0 == len {
return Err("input array len is null\n");
}
while i < len {
buffer.push(array[i]);
index.push(i);
i += 1;
}
i = 0;
while i < len {
while j < len - i - 1 {
if buffer[j] < buffer[j + 1] {
buffer.swap(j, j + 1);
index.swap(j, j + 1);
}
j += 1;
}
i += 1;
}
if buffer[0] >= 2 * buffer[1] {
return Ok(index[0]);
} else {
return Ok(!0 as usize);
}
}
问题描述
给你一个整数数组 nums ,其中总是存在 唯一的 一个最大整数 。
请你找出数组中的最大元素并检查它是否 至少是数组中每个其他数字的两倍 。如果是,则返回 最大元素的下标 ,否则返回 -1 。
示例 1:
输入:nums = [3,6,1,0] 输出:1 解释:6 是最大的整数,对于数组中的其他整数,6 至少是数组中其他元素的两倍。6 的下标是 1 ,所以返回 1 。 示例 2:
输入:nums = [1,2,3,4] 输出:-1 解释:4 没有超过 3 的两倍大,所以返回 -1 。 示例 3:
输入:nums = [1] 输出:0 解释:因为不存在其他数字,所以认为现有数字 1 至少是其他数字的两倍。
提示:
1 <= nums.length <= 50 0 <= nums[i] <= 100 nums 中的最大元素是唯一的
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/largest-number-at-least-twice-of-others