问题描述:{4,5,7,8,1,2} 找值为K的元素。
两种做法,一种常规的稍好于直接查找,另一种为二分o(lgn)
import java.util.Arrays;
public class FindK {
public static void main(String[] args) {
int[] a = { 4, 5, 7, 8, 1, 2 };
int[] b = { 1, 2, 3, 4, 5 };
System.out.println(findK0(a, 5));
System.out.println(findK(a,5));
// System.out.println(findK(a,6));
}
/**
* 折半
* @param a
* @param k
* @return
*/
public static int findK0(int[] a, int k) {
if (a == null)
return -1;
int l = 0, r = a.length;
while (l + 1 < r) {
int m = l + (r - l) / 2;
if (a[m] >= a[l]) {
if (k < a[m]) {
if (k >= a[l])
r = m;
else
l = m;
} else {
l = m;
}
} else {
if (k >= a[m]) {
if (k <= a[r - 1])
l = m;
else
r = m;
} else {
r = m;
}
}
}
return a[l] == k ? l : -1;
}
public static boolean findK(int[] a, int k) {
for (int i = 0; i < a.length; i++) {
if (a[i] == k)
return true;
else if (a[i] > k && i == 0) {
for (int j = a.length; j > i; i--) {
if (a[j] < a[i]) {
if (a[j] == k)
return true;
else if (a[j] < k)
return false;
else if (a[j - 1] > a[j])
return false;
else
continue;
} else
return false;
}
} else {
if (a[i] < a[i + 1] && a[i] < k)
continue;
else
return false;
}
}
return false;
}
}
分享到:
相关推荐
1.数据如下,提取name和callcount 2代码. getQueryCallStatistics(sesp1, this.provinceId).then((res) => { let arr = []; let arr1 = []; let arr2 = [];... this.xunshiMap = res.data.callstatistics;...
LABVIEW对二维数组的某一个值索引,并检索出所有该值所在的行列数
基于labview编写的程序,用于查找数组的最大值以及最小值。
对一维数组进行增删改查:int[] num = new int[10]; 要求:用方法实现 1.输入10个整数 2.删除指定位置上的数 3.修改指定位置上的数 4.查找某个数的位置(下标) 5.查找最大值 6.查找最小值 7.对数组进行排序
cpp代码-测试查找数组最大值
易语言数组中数值的查找源码,数组中数值的查找
主要介绍了php在数组中查找指定值的方法,实例分析了php中array_search函数查找数组指定值的使用技巧,具有一定参考借鉴价值,需要的朋友可以参考下
比较json对象中的两个数组含有的相同元素,点击按钮输出新的数组
1.jquery grep()筛选遍历数组(可以得到反转的数组) // 1.jquery grep()筛选遍历数组(可以得到反转的数组) var array = [1,5,9,3,12,4,48,98,4,75,2,10,11]; var filterArray = $.grep(array,(currentValue) => { ...
易语言快速判断数组中的数值源码,快速判断数组中的数值,是否在数值数组内,拷贝内存_
初学者labview索引数组中的相同元素
检查输入的值是否在数组元素中,并根据查询结果返回对应的值
C# 如何判断一个Byte数组中是否存在某些连续的数据).txtC# 如何判断一个Byte数组中是否存在某些连续的数据).txtC# 如何判断一个Byte数组中是否存在某些连续的数据).txt
本文实例讲述了C语言查找数组里数字重复次数的方法。分享给大家供大家参考。具体如下: #include stdafx.h #include #include using namespace std; int main() { int myarray[10]={4,3,7,4,8,7,9,4,3,6}; ...
IE8不支持indexOf,因此写一个for循环来判断是否存在,下面是代码,经测试还不错
查找函数,能够在输入待查元素后,输出其在数组中的下标; 构造函数,初始化输入数组元素,这里要求数组元素的个数n是一个变量; 析构函数,释放数组元素所占用的堆内存; Set函数,可以为指定的数组元素赋值; Get...
十一、一个维数组,求大于等于数组内的所有值的平均值的个数 例,{1、2、3、4、5、6、7、8、9、10} 输出 5 十二、给一个二维数组inArr[ ][ ],写一个方法获取每一列的最大值,输出到一个一维数组...
使用Linq语法与Lambda表达式分组取泛型数组某列的最小值/最大值
数组a中已存有互不相同的10个整数从键盘输入一个整数,找出与该值相同的数组元素下标。 (如果没找到,输出“没找到”).c