Skip to content

Commit 77ffda8

Browse files
committed
binary search
1 parent c23968f commit 77ffda8

14 files changed

+536
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace BinarySearch.Lib
8+
{
9+
// You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.
10+
11+
//Given n, find the total number of full staircase rows that can be formed.
12+
13+
//n is a non-negative integer and fits within the range of a 32-bit signed integer.
14+
public class ArrangeCoinsSln
15+
{
16+
public int ArrangeCoins(int n)
17+
{
18+
int low = 1, high = n;
19+
while (low < high)
20+
{
21+
//mid的类型,一定防止溢出
22+
int mid = low + (high - low + 1) / 2;
23+
if ((mid + 1) * mid / 2.0 <= n)
24+
low = mid;
25+
else high = mid - 1;
26+
}
27+
return high;
28+
}
29+
}
30+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
4+
<PropertyGroup>
5+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
6+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
7+
<ProjectGuid>{49F28E33-822E-45C0-8F97-7F5AB6121D8B}</ProjectGuid>
8+
<OutputType>Library</OutputType>
9+
<AppDesignerFolder>Properties</AppDesignerFolder>
10+
<RootNamespace>BinarySearch.Lib</RootNamespace>
11+
<AssemblyName>BinarySearch.Lib</AssemblyName>
12+
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
13+
<FileAlignment>512</FileAlignment>
14+
</PropertyGroup>
15+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
16+
<DebugSymbols>true</DebugSymbols>
17+
<DebugType>full</DebugType>
18+
<Optimize>false</Optimize>
19+
<OutputPath>bin\Debug\</OutputPath>
20+
<DefineConstants>DEBUG;TRACE</DefineConstants>
21+
<ErrorReport>prompt</ErrorReport>
22+
<WarningLevel>4</WarningLevel>
23+
</PropertyGroup>
24+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
25+
<DebugType>pdbonly</DebugType>
26+
<Optimize>true</Optimize>
27+
<OutputPath>bin\Release\</OutputPath>
28+
<DefineConstants>TRACE</DefineConstants>
29+
<ErrorReport>prompt</ErrorReport>
30+
<WarningLevel>4</WarningLevel>
31+
</PropertyGroup>
32+
<ItemGroup>
33+
<Reference Include="System" />
34+
<Reference Include="System.Core" />
35+
<Reference Include="System.Xml.Linq" />
36+
<Reference Include="System.Data.DataSetExtensions" />
37+
<Reference Include="Microsoft.CSharp" />
38+
<Reference Include="System.Data" />
39+
<Reference Include="System.Xml" />
40+
</ItemGroup>
41+
<ItemGroup>
42+
<Compile Include="ArrangeCoinsSln.cs" />
43+
<Compile Include="FirstBadVersionSln.cs" />
44+
<Compile Include="IntersectionOfTwoArraysISln.cs" />
45+
<Compile Include="IntersectionOfTwoArraysSln.cs" />
46+
<Compile Include="TwoSumIISln.cs" />
47+
<Compile Include="ValidPerfectSquareSln.cs" />
48+
<Compile Include="Properties\AssemblyInfo.cs" />
49+
</ItemGroup>
50+
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
51+
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
52+
Other similar extension points exist, see Microsoft.Common.targets.
53+
<Target Name="BeforeBuild">
54+
</Target>
55+
<Target Name="AfterBuild">
56+
</Target>
57+
-->
58+
</Project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace BinarySearch.Lib
8+
{
9+
// You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
10+
11+
//Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
12+
13+
//You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
14+
public class FirstBadVersionSln
15+
{
16+
public int FirstBadVersion(int n)
17+
{
18+
long lo = 0; //指向好的版本
19+
long hi = n; //指向坏的版本
20+
long mid;
21+
while (hi - lo > 1)
22+
{
23+
mid = (lo + hi) >> 1; //写为这样就不怕溢出(lo + (hi-lo)/2)
24+
if (IsBadVersion(mid))
25+
hi = mid;
26+
else
27+
lo = mid;
28+
}
29+
return (int)hi;
30+
}
31+
}
32+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace BinarySearch.Lib
8+
{
9+
// Given two arrays, write a function to compute their intersection.
10+
11+
//Example:
12+
13+
//Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
14+
15+
//Note:
16+
17+
//Each element in the result must be unique.
18+
//The result can be in any order.
19+
public class IntersectionOfTwoArraysISln
20+
{
21+
public int[] Intersection(int[] nums1, int[] nums2)
22+
{
23+
if (nums1 == null || nums1.Length == 0) return new int[] { };
24+
if (nums2 == null || nums2.Length == 0) return new int[] { };
25+
return nums1.Intersect(nums2).ToArray();
26+
}
27+
public int[] Intersection(int[] nums1, int[] nums2)
28+
{
29+
if (nums1 == null || nums1.Length == 0) return new int[] { };
30+
if (nums2 == null || nums2.Length == 0) return new int[] { };
31+
HashSet<int> set1 = new HashSet<int>();
32+
foreach (var item in nums1)
33+
{
34+
if (!set1.Contains(item))
35+
set1.Add(item);
36+
}
37+
38+
HashSet<int> set2 = new HashSet<int>();
39+
foreach (var item in nums2)
40+
{
41+
if (!set2.Contains(item))
42+
set2.Add(item);
43+
}
44+
return set1.Intersect(set2).ToArray();
45+
}
46+
}
47+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace BinarySearch.Lib
8+
{
9+
// Given two arrays, write a function to compute their intersection.
10+
11+
//Example:
12+
13+
//Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
14+
// Note:
15+
//Each element in the result should appear as many times as it shows in both arrays.
16+
//The result can be in any order.
17+
//Follow up:
18+
19+
//What if the given array is already sorted? How would you optimize your algorithm?
20+
//What if nums1’s size is small compared to nums2’s size? Which algorithm is better?
21+
//What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
22+
public class IntersectionOfTwoArraysSln
23+
{
24+
//交集定义,元素可重复
25+
public int[] Intersection(int[] nums1, int[] nums2)
26+
{
27+
if (nums1 == null || nums1.Length == 0) return new int[] { };
28+
if (nums2 == null || nums2.Length == 0) return new int[] { };
29+
nums1 = nums1.OrderBy(r => r).ToArray(); //升序排列
30+
nums2 = nums2.OrderBy(r => r).ToArray();
31+
32+
int n = nums1.Length < nums2.Length ? nums1.Length : nums2.Length;
33+
List<int> rtn = new List<int>();
34+
if (nums1.Length < nums2.Length)
35+
{
36+
rtn = getIntersection(nums1, nums2);
37+
}
38+
else
39+
rtn = getIntersection(nums2, nums1);
40+
return rtn.ToArray();
41+
}
42+
43+
//二分查找插入位置(相等元素,新插入位置靠后)
44+
//beginIndex:查询的起始位置
45+
private int searchInsertIndex(int[] sorted, int lo, int e)
46+
{
47+
int hi = sorted.Length;
48+
while (lo < hi)
49+
{
50+
int mi = (lo + hi) >> 1;
51+
if (e < sorted[mi])
52+
hi = mi;
53+
else
54+
lo = mi + 1;
55+
}
56+
return lo;
57+
}
58+
59+
//nums1个数小于后者得到交集
60+
private List<int> getIntersection(int[] nums1, int[] nums2)
61+
{
62+
List<int> rtn = new List<int>();
63+
int index = 0;
64+
for (int i = 0; i < nums1.Length; i++)
65+
{
66+
index = searchInsertIndex(nums2, index, nums1[i]);
67+
if (index <= 0) //nums2中一定不存在这个元素
68+
continue;
69+
if (nums1[i] == nums2[index - 1])
70+
{
71+
rtn.Add(nums1[i]);
72+
int precnt = preSame(nums2, index - 1);
73+
int succnt = sucSame(nums1, i);
74+
int sml = precnt < succnt ? precnt : succnt;
75+
while (sml-- > 0)
76+
rtn.Add(nums1[i]);
77+
if (succnt > 0)
78+
i = i + succnt;
79+
}
80+
}
81+
return rtn;
82+
}
83+
84+
//有序数组中向<----后搜索相等元素的个数
85+
private int preSame(int[] nums, int index)
86+
{
87+
int sameCnt = 0;
88+
for (int i = index; i > 0; i--)
89+
{
90+
if (nums[index] == nums[i - 1])
91+
sameCnt++;
92+
}
93+
return sameCnt;
94+
}
95+
96+
//有序数组中向<----前搜索相等元素的个数
97+
private int sucSame(int[] nums, int index)
98+
{
99+
int sameCnt = 0;
100+
for (int i = index; i < nums.Length - 1; i++)
101+
{
102+
if (nums[index] == nums[i + 1])
103+
sameCnt++;
104+
}
105+
return sameCnt;
106+
}
107+
108+
}
109+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// 有关程序集的常规信息通过以下
6+
// 特性集控制。更改这些特性值可修改
7+
// 与程序集关联的信息。
8+
[assembly: AssemblyTitle("BinarySearch.Lib")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("BinarySearch.Lib")]
13+
[assembly: AssemblyCopyright("Copyright © 2017")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// 将 ComVisible 设置为 false 使此程序集中的类型
18+
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
19+
// 则将该类型上的 ComVisible 特性设置为 true。
20+
[assembly: ComVisible(false)]
21+
22+
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
23+
[assembly: Guid("85a160d4-ffcc-4c51-b57f-6a4731b32bc7")]
24+
25+
// 程序集的版本信息由下面四个值组成:
26+
//
27+
// 主版本
28+
// 次版本
29+
// 生成号
30+
// 修订号
31+
//
32+
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
33+
// 方法是按如下所示使用“*”:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace BinarySearch.Lib
8+
{
9+
// Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
10+
11+
//The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
12+
13+
//You may assume that each input would have exactly one solution and you may not use the same element twice.
14+
15+
//Input: numbers={2, 7, 11, 15}, target=9
16+
//Output: index1=1, index2=2
17+
public class TwoSumIISln
18+
{
19+
public int[] TwoSum(int[] num, int target)
20+
{
21+
//因为一定存在解,所以不做边界检查
22+
int left = 0, right = num.Length - 1;
23+
while (left < right)
24+
{
25+
int v = num[left] + num[right];
26+
if (v == target)
27+
return new int[2] { left + 1, right + 1 };
28+
else if (v > target)
29+
right--;
30+
else
31+
left++;
32+
}
33+
return new int[] { };
34+
}
35+
36+
}
37+
}

0 commit comments

Comments
 (0)