数组查值

问题描述:{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;
	}

}
 
在不同编程语言中,数组查询指定值有不同的API,以下以常见的JavaScript和Python为例进行介绍。 ### JavaScript 在JavaScript中,可使用`indexOf()`方法来查询指定值在数组中的位置。如果找到指定值,该方法返回其第一次出现的索引;若未找到,则返回 -1。示例代码如下: ```javascript var arr = [1, 2, 3, 4]; var a = arr.indexOf(2); console.log(a); // 输出:1 (元素'2'位于数组下标为1的位置) ``` 此外,还有`find()`和`findIndex()`方法: - `find()`:返回数组中满足提供的测试函数的第一个元素的值,否则返回`undefined`。 ```javascript let posts = [ { id: 3, title: "Node.js" }, { id: 1, title: "React.js" } ]; let comment = { postId: 1, content: "Hello World!" }; function postForComment(posts, comment) { return posts.find(function (post) { return post.id === comment.postId; }); } console.log(postForComment(posts, comment)); // {id: 1, title: "React.js"} ``` - `findIndex()`:返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素,则返回 -1。 ```javascript let numbers = [10, 20, 30, 40]; let index = numbers.findIndex(num => num > 25); console.log(index); // 输出:2 ``` ### Python 在Python中,可使用`index()`方法来查询指定值在列表(类似于其他语言的数组)中的位置。若指定值存在于列表中,返回其第一次出现的索引;若不存在,则抛出`ValueError`异常。示例代码如下: ```python my_list = [10, 20, 30, 40] try: index = my_list.index(20) print(index) # 输出:1 except ValueError: print("指定值不在列表中") ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值