Sorting&Searching 二分法找有空字符串的数组 @CareerCup

用二分法查找数组中的元素 用二分法查找数组中的某个元素,首先数组中的元素必须是有序的,然后查找想要的元素,返回其下标值。 #include <stdio.h> int BinSerach(int arr[],int len,int key) { int low=0; int high=len-1; int mid; while(low<=high) { mid==(low+hi... 阅读详情

要点是找到最近的不是空字符串的位置,然后作为mid,再继续二分


package Sorting_Searching;

/**
 * Given a sorted array of strings which is interspersed with empty strings,
 * write a method to find the location of a given string.
 * 
 * Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”,“”,
 * “dad”, “”, “”] will return 4
 * 
 * Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”,
 * “dad”, “”, “”] will return -1
 * 
 * 译文:
 * 
 * 给你一个排好序的并且穿插有空字符串的字符串数组,写一个函数找到给定字符串的位置。
 * 
 * 例子:在字符串数组 [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”,“”, “dad”, “”, “”]
 * 中找到"ball",返回下标4.
 * 
 * 例子:在字符串数组 [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”]
 * 中找到"ballcar",查找失败,返回-1.
 * 
 */
public class S11_5 {

	public static void main(String[] args) {
		String[] stringList = { "apple", "", "", "banana", "", "", "",
				"carrot", "duck", "", "", "eel", "", "flower" };
		System.out.println(search(stringList, "apple"));
	}

	public static int search(String[] strings, String str) {
		if (strings == null || str == null || str.isEmpty()) {
			return -1;
		}
		return searchR(strings, str, 0, strings.length - 1);
	}
	
	public static int searchR(String[] strings, String str, int first, int last) {
		if(first > last){
			return -1;
		}
		
		int mid = (first+last)/2;
		
		// 找到离中心最近的不是空字符串的位置
		if(strings[mid].length() == 0 && mid<=last){
			int left = mid-1;
			int right = mid+1;
			while(true){
				if(left<first && right>last){
					return -1;
				}else if(right<=last && strings[right].length()!=0){
					mid = right;
					break;
				}else if(left>=first && strings[left].length()!=0){
					mid = left;
					break;
				}
				right++;
				left--;
			}
		}
		
		if(str.equals(strings[mid])){
			return mid;
		}else if(strings[mid].compareTo(str) > 0){
			return searchR(strings, str, first, mid-1);
		}else {
			return searchR(strings, str, mid+1, last);
		}
	}
}


GPT-5.6、Qwen 4、Grok 4.5三大AI模型技术对比与开发实践指南 AI编程助手作为提升开发效率的重要工具,其核心原理是基于大语言模型的代码生成与理解能力。通过深度学习技术,这些模型能够理解编程语言的语法结构和逻辑关系,为开发者提供智能代码补全、错误检测和文档生成等功能。在技术价值层面,AI编程助手可以显著减少重复性编码工作,提高代码质量和开发效率。在实际应用场景中,不同模型在特定领域表现出差异化优势:GPT-5.6在通用编程任务上表现稳定,Qwen 4对中文开发环境有深度优化,而Grok 4.5则在代码生成专项任务上表现突出。本文基于实际测试数据,从开发效率提升、技术选型 阅读详情

相关推荐

Python:实现searching in sorted matrix在排序矩阵中搜索算法(附完整源码)

Python:实现searching in sorted matrix在排序矩阵中搜索算法(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 466

[Leetcode][python]Convert Sorted List to Binary Search Tree

题目大意将一个升序链表转为有序二叉树 和上一题的不同仅仅是将数组换成了链表解题思路 首先想到的是将链表存入数组,然后和上一题相同。 网上思路是用快慢指针,慢指针每次走一格,快指针每次走两格 代码转为数组(街上一题)# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): #

蛮三刀酱 1927

人大金仓数据库Kingbase FlySync同步程序安装

Kingbase FlySync同步程序(以下简称 KFS)是面向异地容灾、数据集中共享的场景推出的具备在异构数据平台间实现实时、增量数据同步的工具类产品,主要采用了物理日志解析技术,帮助用户解决不同数据平台的数据间可实现任意方向实时移动流转的问题,并保证此过程中数据不丢失,状态可监控,流转数据量可统计。KFS 需要安装的主要组件有 2 个,分别是后端同步程序和管理控制平台,另外KFS的部署方式也有2种,为分离部署何集中部署•集中部署:KFS与数据库部署在同一机器上。

weixin_44312518的博客 1178

C语言二分法查找数组

代码不是我滴也算是我滴是久久/九九的,这是久久大一2016年写的..... #include<stdio.h> int fun(int a[],int num,int n) { int left=0; int right=n-1; int mid=(left+right)/2; while (1) { if (num==a[left]) return left; if (num==a...

温和的跳跃 5917

专题一:Labview表格控件 及 应用(三)在表格中插入一行数据

专题一:Labview表格控件 及 应用(三) 在表格中插入一行数据 最近一段时间,做试验台上位机编程,老是用到表格控件,这几天抽时间专门写一个表格控件的专题。有用到的朋友可以参考一下。 今天接着讲一下,表格控件的数据插入,和相关的操作 1.表格控件的数据插入原理: 表格控件是一个 2D 字符串数组。 在表格插入一行,就是在2D数组插入一行。 行、列插入类似** 以下以成绩录入为例说明 2.1 不要表头直接插入 知识点1:创建数组:把数学,语文,英语三个数值,连成一个一位数组(数值型)。 知

Labview十年工控_702老师的博客 1万+

Mem0 vs LangMem vs Letta:三大AI记忆框架实战对比(附代码示例)

本文深入对比了Mem0、LangMem和Letta三大AI记忆框架的核心特性与适用场景。Mem0提供开箱即用的记忆管理服务,适合快速集成;LangMem深度融入LangGraph生态,适合复杂工作流;Letta则采用虚拟内存系统,旨在突破上下文窗口限制。文章通过实战代码示例,为开发者选择适合其业务需求的AI记忆解决方案提供了清晰指南。

g9h0i1的博客 679

c# sortedlist_我如何发现C#SortedList使用二进制搜索以及为什么要关心

c# sortedlistby Rina Artstain 通过丽娜·阿斯特斯坦 我如何发现C#SortedList使用二进制搜索以及为什么要关心 (How I Discovered that C# SortedList Uses Binary Search, and Why You Should Care) There is an age old debate: can programmer...

242

NU1680无线充电接收器在TWS耳机中的应用实战:I2C调压与QI协议适配

本文详细解析了NU1680无线充电接收器在TWS耳机充电仓设计中的应用实战。重点阐述了其无固件设计、I2C接口动态调压功能如何解决不同QI协议发射器的兼容性难题,并分享了硬件设计、PCB布局、与发射端联调及安全测试等关键环节的实践经验,助力开发者快速实现稳定高效的无线充电方案。

weixin_28432777的博客 231

找出字符串

题目描述 有一个排过序的字符串数组,但是其中有插入了一些空字符串,请设计一个算法,找出给定字符串的位置。算法的查找部分的复杂度应该为log级别。 给定一个string数组str,同时给定数组大小n和需要查找的stringx,请返回该串的位置(位置从零开始)。 测试样例: ["a","b","","c","","d"],6,"c" 返回:3 变形的二分查找,重新设定了mid...

lMonster81 347

Neo4j Desktop新手必看:3分钟搞定CSV数据导入(附常见报错解决方案)

本文详细介绍了在Neo4j Desktop中高效导入CSV数据的三种主流方法,包括图形化界面操作、命令行批量导入和Python驱动编程导入,并提供了常见报错解决方案和性能优化技巧,帮助新手快速构建知识图谱。

lambda的博客 648

SystemVerilog学习总结

因为选择的offer是IC验证,以前学的是设计,所以只能再学systemverilog(SV)和UVM了。在学习SV和UVM之前,我认为需要学习以下几个部分:数字电路、c++和verilog。因为IC验证确实有不少别的专业之前没学过数字电路和Verilog,所以还是最好先学习一下。 知识点的总结主要是通过systemverilog验证-测试平台编写指南这本书进行的,所以请看书。通过对这本书的目录进行重点的划分,然后再进行相关知识点的总结。最后,给出自己收集的别的博主IC EDA环境的虚拟机,以及使用虚拟机需

博主毕竟还是人,肯定会有错误,各位看的时候发现错误提出来就好 1万+

Sorting&Searching 基于变位词的字符串数组排序 @CareerCup

两种排序结果不一样。。。 1 实现Comparator接口的compare方法,在里面先把每个string都排序一遍,然后再比较 2 用一个Hashtable>的结构,String为排序后的确定的string,LL里面装着各种anagram的变种 package Sorting_Searching; import java.util.Arrays; import java.util

2132

ESP32-C3入门教程 基础篇⑩——SNTP(Simple Network Time Protocol) 网络时间同步的简单实例

ESP32-C3入门教程 基础篇⑩——SNTP(Simple Network Time Protocol) 网络时间同步的简单实例

1589

Searching and Sorting - qsort

前言在逆向cm时, 看到人家排序用到了qsort. 从来没用过…, 做个试验.记录// test1958.cpp : Defines the entry point for the console application. // Searching and Sorting - qsort#include "stdafx.h" #include <windows.h>/* QSORT.C: Th

博客标题不能为空 612

基于ESP32 蓝牙游戏手柄设计

介绍使用 ESP32 并通过 BLE 通信的 设计手持游戏手柄,包含原理图与代码

DT程序员的博客 2163

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

convert-sorted-list-to-binary-search-tree

题目描述 Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 思路:通过快慢指针找到中间结点,将中间结点插入到二叉搜索树中,然后从中间将有序单链表拆成两部分,前半部分递归为左子树,后半部分递归为右子树。 /** * Def...

fistraiser的博客 190

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

Hard 单词变型成另一个单词 @CareerCup

对起始单词的每一个字母都做替换,把替换后的单词加入到queue中,并同时维护一个Map来记录变化前单词和变化后单词的联系。用来回溯时能打印出路径。 package Hard; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; impor

4761

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

Hard 找到由其它单词组成的最长单词 @CareerCup

用DFS的那个模板就能做出来,值得注意的是一个词必须被除自己外的其他词组成才行,不能是自己组成自己。 package Hard; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import CtCILibrary.A

3649

Tree_Graph 判断T2是否为T1的子树 @CareerCup

原文: You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1 译文: 有两棵很大的二叉树:T1有上百万个结点,T2有上百个结点。写

3486

Stack_Queue 把栈排序 Sort a stack @CareerCup

原文: Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write thi

3231

Stack_Queue 猫狗队列问题 Cat dog queue @CareerCup

An animal shelter holds only dogs and cats, and operates ona strictly “first in, first out” basis. People must adopt either the “oldest”(based on arrival time) of all animals at the shelter, or they

3092

Recursion 字符串的全排列 String Permutation @CareerCup

字符串全排列的题目,还是套用模板,同样要注意ret的size问题会变化。而且与上一题不同的是不光是要在ret后面添加进新的组合,而且还要移除前面用过的组合。类似一个队列。 另外Java的substring中区间闭合情况是左闭右开 [ ) 所以想把一个字符串拆成两个区间就可以用这一句: for(int j=0; j<=tmp.length(); j++){ // substring

2977

Moderate 判断井字游戏的胜利 @CareerCup

基于要查找的次数来决定是否要预处理。预处理方式按照3进制来做。 另外,检查是否赢了要判断横行,纵列,正反对角线 package Moderate; /** * Design an algorithm to figure out if someone has won in a game of tic-tac-toe. 译文: 设计算法检查某人是否赢得了井字游戏。 *

2970

LinkLists 检查一个链表是否为回文 Check if a linked list is palindrome @CareerCup

Implement a function to check a linked list is a palindrome 检查一个链表是否为回文 思路: 1 Iterative,利用栈,把链表前半段存入栈,再逐个弹栈和链表后半段比较。注意链表长度为奇数的情况!要跳过中间节点! 2 递归! 定义递归函数为 Result rec(LinkedListNode head, int l

2921

Tree_Graph LCA(Lowest Common Ancestor) 最低公共节点 (BST或者一般树) @CareerCup

原文: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary se

2627

Sorting_Searching 叠罗汉 @CareerCup

类似前面的一道堆箱子 普适的解法是回溯,注意这类是求最值的回溯题。 另一种解法是LIS,先把其中一维排序,然后对剩下的一维进行LIS package Sorting_Searching; import java.util.ArrayList; import java.util.Collections; /** * A circus is designing a tower r

2461
上一篇: Sorting&Searching 旋转数组二分法查找 @CareerCup
下一篇: Sorting_Searching 有序矩阵中查找数 @CareerCup
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值