LeetCode
- Subject: Searching for Insertion
Given a sorted array and a target value , find the target value in the array and return its index . If the target value does not exist in the array, returns the position where it will be inserted in order. Please use an O(log n) algorithm.
- Problem solving ideas
① First consider the case where the target number is the first or before the first number
②Consider the case where the target number is not in the array and after the last number
③ When considering the target number in the array or the position where it should be inserted in order
[ Knowledge points ] array, for loop, if judgment, break
- result
public class LeetCodePrac { public static void main(String[] args) { int[] nums = { 1,2,4,5 }; System.out.println(searchInsert(nums, -1)); } public static int searchInsert(int[] nums, int target) { int index = -1; int len = nums.length; if (nums[0] >= target) { return 0; } else if (nums[len - 1] < target) { return len; } for (int i = 1; i < len; i++) { if (nums[i - 1] < target & nums[i] >= target) { index = i; break; } } return index; }
nowcoder
- Topic: Create an index idx_emp_no for the emp_no field of the salaries table above
The salaries table has been created, the index idx_emp_no is created for the emp_no field, the query emp_no is 10005, and the mandatory index is used .
CREATE TABLE `salaries` ( `emp_no` int(11) NOT NULL, `salary` int(11) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`emp_no`,`from_date`)); create index idx_emp_no on salaries(emp_no); INSERT INTO salaries VALUES(10005,78228,'1989-09-12','1990-09-12'); INSERT INTO salaries VALUES(10005,94692,'2001-09-09','9999-01-01');
- Problem solving ideas
【Knowledge points】
①SQL table query
SELECT * FROM <表名> SELECT * FROM <表名> WHERE <字段名> [查询条件] <值>
② SQL forced index
SELECT * FROM <表名> FORCE INDEX (<索引名>) WHERE <字段名> [查询条件] <值>
- code
select * from salaries FORCE INDEX (idx_emp_no) WHERE emp_no=10005